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            self.executor
1821                .block(tx.send(ScanJob {
1822                    abs_path: abs_path.to_path_buf(),
1823                    path,
1824                    ignore_stack: IgnoreStack::none(),
1825                    scan_queue: tx.clone(),
1826                }))
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        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
1951        events.dedup_by(|a, b| a.path.starts_with(&b.path));
1952
1953        let root_char_bag;
1954        let root_abs_path;
1955        let next_entry_id;
1956        {
1957            let mut snapshot = self.snapshot.lock();
1958            snapshot.scan_id += 1;
1959            root_char_bag = snapshot.root_char_bag;
1960            root_abs_path = snapshot.abs_path.clone();
1961            next_entry_id = snapshot.next_entry_id.clone();
1962        }
1963
1964        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&root_abs_path).await {
1965            abs_path
1966        } else {
1967            return false;
1968        };
1969        let metadata = futures::future::join_all(
1970            events
1971                .iter()
1972                .map(|event| self.fs.metadata(&event.path))
1973                .collect::<Vec<_>>(),
1974        )
1975        .await;
1976
1977        // Hold the snapshot lock while clearing and re-inserting the root entries
1978        // for each event. This way, the snapshot is not observable to the foreground
1979        // thread while this operation is in-progress.
1980        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
1981        {
1982            let mut snapshot = self.snapshot.lock();
1983            for event in &events {
1984                if let Ok(path) = event.path.strip_prefix(&root_abs_path) {
1985                    snapshot.remove_path(&path);
1986                }
1987            }
1988
1989            for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
1990                let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
1991                    Ok(path) => Arc::from(path.to_path_buf()),
1992                    Err(_) => {
1993                        log::error!(
1994                            "unexpected event {:?} for root path {:?}",
1995                            event.path,
1996                            root_abs_path
1997                        );
1998                        continue;
1999                    }
2000                };
2001
2002                match metadata {
2003                    Ok(Some(metadata)) => {
2004                        let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2005                        let mut fs_entry = Entry::new(
2006                            path.clone(),
2007                            &metadata,
2008                            snapshot.next_entry_id.as_ref(),
2009                            snapshot.root_char_bag,
2010                        );
2011                        fs_entry.is_ignored = ignore_stack.is_all();
2012                        snapshot.insert_entry(fs_entry, self.fs.as_ref());
2013                        if metadata.is_dir {
2014                            self.executor
2015                                .block(scan_queue_tx.send(ScanJob {
2016                                    abs_path: event.path,
2017                                    path,
2018                                    ignore_stack,
2019                                    scan_queue: scan_queue_tx.clone(),
2020                                }))
2021                                .unwrap();
2022                        }
2023                    }
2024                    Ok(None) => {}
2025                    Err(err) => {
2026                        // TODO - create a special 'error' entry in the entries tree to mark this
2027                        log::error!("error reading file on event {:?}", err);
2028                    }
2029                }
2030            }
2031            drop(scan_queue_tx);
2032        }
2033
2034        // Scan any directories that were created as part of this event batch.
2035        self.executor
2036            .scoped(|scope| {
2037                for _ in 0..self.executor.num_cpus() {
2038                    scope.spawn(async {
2039                        while let Ok(job) = scan_queue_rx.recv().await {
2040                            if let Err(err) = self
2041                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2042                                .await
2043                            {
2044                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2045                            }
2046                        }
2047                    });
2048                }
2049            })
2050            .await;
2051
2052        // Attempt to detect renames only over a single batch of file-system events.
2053        self.snapshot.lock().removed_entry_ids.clear();
2054
2055        self.update_ignore_statuses().await;
2056        true
2057    }
2058
2059    async fn update_ignore_statuses(&self) {
2060        let mut snapshot = self.snapshot();
2061
2062        let mut ignores_to_update = Vec::new();
2063        let mut ignores_to_delete = Vec::new();
2064        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2065            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2066                ignores_to_update.push(parent_path.clone());
2067            }
2068
2069            let ignore_path = parent_path.join(&*GITIGNORE);
2070            if snapshot.entry_for_path(ignore_path).is_none() {
2071                ignores_to_delete.push(parent_path.clone());
2072            }
2073        }
2074
2075        for parent_path in ignores_to_delete {
2076            snapshot.ignores.remove(&parent_path);
2077            self.snapshot.lock().ignores.remove(&parent_path);
2078        }
2079
2080        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2081        ignores_to_update.sort_unstable();
2082        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2083        while let Some(parent_path) = ignores_to_update.next() {
2084            while ignores_to_update
2085                .peek()
2086                .map_or(false, |p| p.starts_with(&parent_path))
2087            {
2088                ignores_to_update.next().unwrap();
2089            }
2090
2091            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2092            ignore_queue_tx
2093                .send(UpdateIgnoreStatusJob {
2094                    path: parent_path,
2095                    ignore_stack,
2096                    ignore_queue: ignore_queue_tx.clone(),
2097                })
2098                .await
2099                .unwrap();
2100        }
2101        drop(ignore_queue_tx);
2102
2103        self.executor
2104            .scoped(|scope| {
2105                for _ in 0..self.executor.num_cpus() {
2106                    scope.spawn(async {
2107                        while let Ok(job) = ignore_queue_rx.recv().await {
2108                            self.update_ignore_status(job, &snapshot).await;
2109                        }
2110                    });
2111                }
2112            })
2113            .await;
2114    }
2115
2116    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2117        let mut ignore_stack = job.ignore_stack;
2118        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2119            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2120        }
2121
2122        let mut entries_by_id_edits = Vec::new();
2123        let mut entries_by_path_edits = Vec::new();
2124        for mut entry in snapshot.child_entries(&job.path).cloned() {
2125            let was_ignored = entry.is_ignored;
2126            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2127            if entry.is_dir() {
2128                let child_ignore_stack = if entry.is_ignored {
2129                    IgnoreStack::all()
2130                } else {
2131                    ignore_stack.clone()
2132                };
2133                job.ignore_queue
2134                    .send(UpdateIgnoreStatusJob {
2135                        path: entry.path.clone(),
2136                        ignore_stack: child_ignore_stack,
2137                        ignore_queue: job.ignore_queue.clone(),
2138                    })
2139                    .await
2140                    .unwrap();
2141            }
2142
2143            if entry.is_ignored != was_ignored {
2144                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2145                path_entry.scan_id = snapshot.scan_id;
2146                path_entry.is_ignored = entry.is_ignored;
2147                entries_by_id_edits.push(Edit::Insert(path_entry));
2148                entries_by_path_edits.push(Edit::Insert(entry));
2149            }
2150        }
2151
2152        let mut snapshot = self.snapshot.lock();
2153        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2154        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2155    }
2156}
2157
2158async fn refresh_entry(
2159    fs: &dyn Fs,
2160    snapshot: &Mutex<LocalSnapshot>,
2161    path: Arc<Path>,
2162    abs_path: &Path,
2163    old_path: Option<Arc<Path>>,
2164) -> Result<Entry> {
2165    let root_char_bag;
2166    let next_entry_id;
2167    {
2168        let snapshot = snapshot.lock();
2169        root_char_bag = snapshot.root_char_bag;
2170        next_entry_id = snapshot.next_entry_id.clone();
2171    }
2172    let entry = Entry::new(
2173        path,
2174        &fs.metadata(abs_path)
2175            .await?
2176            .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
2177        &next_entry_id,
2178        root_char_bag,
2179    );
2180    let mut snapshot = snapshot.lock();
2181    if let Some(old_path) = old_path {
2182        snapshot.remove_path(&old_path);
2183    }
2184    Ok(snapshot.insert_entry(entry, fs))
2185}
2186
2187fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2188    let mut result = root_char_bag;
2189    result.extend(
2190        path.to_string_lossy()
2191            .chars()
2192            .map(|c| c.to_ascii_lowercase()),
2193    );
2194    result
2195}
2196
2197struct ScanJob {
2198    abs_path: PathBuf,
2199    path: Arc<Path>,
2200    ignore_stack: Arc<IgnoreStack>,
2201    scan_queue: Sender<ScanJob>,
2202}
2203
2204struct UpdateIgnoreStatusJob {
2205    path: Arc<Path>,
2206    ignore_stack: Arc<IgnoreStack>,
2207    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2208}
2209
2210pub trait WorktreeHandle {
2211    #[cfg(any(test, feature = "test-support"))]
2212    fn flush_fs_events<'a>(
2213        &self,
2214        cx: &'a gpui::TestAppContext,
2215    ) -> futures::future::LocalBoxFuture<'a, ()>;
2216}
2217
2218impl WorktreeHandle for ModelHandle<Worktree> {
2219    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2220    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2221    // extra directory scans, and emit extra scan-state notifications.
2222    //
2223    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2224    // to ensure that all redundant FS events have already been processed.
2225    #[cfg(any(test, feature = "test-support"))]
2226    fn flush_fs_events<'a>(
2227        &self,
2228        cx: &'a gpui::TestAppContext,
2229    ) -> futures::future::LocalBoxFuture<'a, ()> {
2230        use smol::future::FutureExt;
2231
2232        let filename = "fs-event-sentinel";
2233        let tree = self.clone();
2234        let (fs, root_path) = self.read_with(cx, |tree, _| {
2235            let tree = tree.as_local().unwrap();
2236            (tree.fs.clone(), tree.abs_path().clone())
2237        });
2238
2239        async move {
2240            fs.create_file(&root_path.join(filename), Default::default())
2241                .await
2242                .unwrap();
2243            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2244                .await;
2245
2246            fs.remove_file(&root_path.join(filename), Default::default())
2247                .await
2248                .unwrap();
2249            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2250                .await;
2251
2252            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2253                .await;
2254        }
2255        .boxed_local()
2256    }
2257}
2258
2259#[derive(Clone, Debug)]
2260struct TraversalProgress<'a> {
2261    max_path: &'a Path,
2262    count: usize,
2263    visible_count: usize,
2264    file_count: usize,
2265    visible_file_count: usize,
2266}
2267
2268impl<'a> TraversalProgress<'a> {
2269    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2270        match (include_ignored, include_dirs) {
2271            (true, true) => self.count,
2272            (true, false) => self.file_count,
2273            (false, true) => self.visible_count,
2274            (false, false) => self.visible_file_count,
2275        }
2276    }
2277}
2278
2279impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2280    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2281        self.max_path = summary.max_path.as_ref();
2282        self.count += summary.count;
2283        self.visible_count += summary.visible_count;
2284        self.file_count += summary.file_count;
2285        self.visible_file_count += summary.visible_file_count;
2286    }
2287}
2288
2289impl<'a> Default for TraversalProgress<'a> {
2290    fn default() -> Self {
2291        Self {
2292            max_path: Path::new(""),
2293            count: 0,
2294            visible_count: 0,
2295            file_count: 0,
2296            visible_file_count: 0,
2297        }
2298    }
2299}
2300
2301pub struct Traversal<'a> {
2302    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2303    include_ignored: bool,
2304    include_dirs: bool,
2305}
2306
2307impl<'a> Traversal<'a> {
2308    pub fn advance(&mut self) -> bool {
2309        self.advance_to_offset(self.offset() + 1)
2310    }
2311
2312    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2313        self.cursor.seek_forward(
2314            &TraversalTarget::Count {
2315                count: offset,
2316                include_dirs: self.include_dirs,
2317                include_ignored: self.include_ignored,
2318            },
2319            Bias::Right,
2320            &(),
2321        )
2322    }
2323
2324    pub fn advance_to_sibling(&mut self) -> bool {
2325        while let Some(entry) = self.cursor.item() {
2326            self.cursor.seek_forward(
2327                &TraversalTarget::PathSuccessor(&entry.path),
2328                Bias::Left,
2329                &(),
2330            );
2331            if let Some(entry) = self.cursor.item() {
2332                if (self.include_dirs || !entry.is_dir())
2333                    && (self.include_ignored || !entry.is_ignored)
2334                {
2335                    return true;
2336                }
2337            }
2338        }
2339        false
2340    }
2341
2342    pub fn entry(&self) -> Option<&'a Entry> {
2343        self.cursor.item()
2344    }
2345
2346    pub fn offset(&self) -> usize {
2347        self.cursor
2348            .start()
2349            .count(self.include_dirs, self.include_ignored)
2350    }
2351}
2352
2353impl<'a> Iterator for Traversal<'a> {
2354    type Item = &'a Entry;
2355
2356    fn next(&mut self) -> Option<Self::Item> {
2357        if let Some(item) = self.entry() {
2358            self.advance();
2359            Some(item)
2360        } else {
2361            None
2362        }
2363    }
2364}
2365
2366#[derive(Debug)]
2367enum TraversalTarget<'a> {
2368    Path(&'a Path),
2369    PathSuccessor(&'a Path),
2370    Count {
2371        count: usize,
2372        include_ignored: bool,
2373        include_dirs: bool,
2374    },
2375}
2376
2377impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2378    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2379        match self {
2380            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2381            TraversalTarget::PathSuccessor(path) => {
2382                if !cursor_location.max_path.starts_with(path) {
2383                    Ordering::Equal
2384                } else {
2385                    Ordering::Greater
2386                }
2387            }
2388            TraversalTarget::Count {
2389                count,
2390                include_dirs,
2391                include_ignored,
2392            } => Ord::cmp(
2393                count,
2394                &cursor_location.count(*include_dirs, *include_ignored),
2395            ),
2396        }
2397    }
2398}
2399
2400struct ChildEntriesIter<'a> {
2401    parent_path: &'a Path,
2402    traversal: Traversal<'a>,
2403}
2404
2405impl<'a> Iterator for ChildEntriesIter<'a> {
2406    type Item = &'a Entry;
2407
2408    fn next(&mut self) -> Option<Self::Item> {
2409        if let Some(item) = self.traversal.entry() {
2410            if item.path.starts_with(&self.parent_path) {
2411                self.traversal.advance_to_sibling();
2412                return Some(item);
2413            }
2414        }
2415        None
2416    }
2417}
2418
2419impl<'a> From<&'a Entry> for proto::Entry {
2420    fn from(entry: &'a Entry) -> Self {
2421        Self {
2422            id: entry.id.to_proto(),
2423            is_dir: entry.is_dir(),
2424            path: entry.path.to_string_lossy().to_string(),
2425            inode: entry.inode,
2426            mtime: Some(entry.mtime.into()),
2427            is_symlink: entry.is_symlink,
2428            is_ignored: entry.is_ignored,
2429        }
2430    }
2431}
2432
2433impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2434    type Error = anyhow::Error;
2435
2436    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2437        if let Some(mtime) = entry.mtime {
2438            let kind = if entry.is_dir {
2439                EntryKind::Dir
2440            } else {
2441                let mut char_bag = root_char_bag.clone();
2442                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
2443                EntryKind::File(char_bag)
2444            };
2445            let path: Arc<Path> = Arc::from(Path::new(&entry.path));
2446            Ok(Entry {
2447                id: ProjectEntryId::from_proto(entry.id),
2448                kind,
2449                path: path.clone(),
2450                inode: entry.inode,
2451                mtime: mtime.into(),
2452                is_symlink: entry.is_symlink,
2453                is_ignored: entry.is_ignored,
2454            })
2455        } else {
2456            Err(anyhow!(
2457                "missing mtime in remote worktree entry {:?}",
2458                entry.path
2459            ))
2460        }
2461    }
2462}
2463
2464#[cfg(test)]
2465mod tests {
2466    use super::*;
2467    use crate::fs::FakeFs;
2468    use anyhow::Result;
2469    use client::test::FakeHttpClient;
2470    use fs::RealFs;
2471    use rand::prelude::*;
2472    use serde_json::json;
2473    use std::{
2474        env,
2475        fmt::Write,
2476        time::{SystemTime, UNIX_EPOCH},
2477    };
2478    use util::test::temp_tree;
2479
2480    #[gpui::test]
2481    async fn test_traversal(cx: &mut gpui::TestAppContext) {
2482        let fs = FakeFs::new(cx.background());
2483        fs.insert_tree(
2484            "/root",
2485            json!({
2486               ".gitignore": "a/b\n",
2487               "a": {
2488                   "b": "",
2489                   "c": "",
2490               }
2491            }),
2492        )
2493        .await;
2494
2495        let http_client = FakeHttpClient::with_404_response();
2496        let client = Client::new(http_client);
2497
2498        let tree = Worktree::local(
2499            client,
2500            Arc::from(Path::new("/root")),
2501            true,
2502            fs,
2503            Default::default(),
2504            &mut cx.to_async(),
2505        )
2506        .await
2507        .unwrap();
2508        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2509            .await;
2510
2511        tree.read_with(cx, |tree, _| {
2512            assert_eq!(
2513                tree.entries(false)
2514                    .map(|entry| entry.path.as_ref())
2515                    .collect::<Vec<_>>(),
2516                vec![
2517                    Path::new(""),
2518                    Path::new(".gitignore"),
2519                    Path::new("a"),
2520                    Path::new("a/c"),
2521                ]
2522            );
2523        })
2524    }
2525
2526    #[gpui::test]
2527    async fn test_rescan_with_gitignore(cx: &mut gpui::TestAppContext) {
2528        let dir = temp_tree(json!({
2529            ".git": {},
2530            ".gitignore": "ignored-dir\n",
2531            "tracked-dir": {
2532                "tracked-file1": "tracked contents",
2533            },
2534            "ignored-dir": {
2535                "ignored-file1": "ignored contents",
2536            }
2537        }));
2538
2539        let http_client = FakeHttpClient::with_404_response();
2540        let client = Client::new(http_client.clone());
2541
2542        let tree = Worktree::local(
2543            client,
2544            dir.path(),
2545            true,
2546            Arc::new(RealFs),
2547            Default::default(),
2548            &mut cx.to_async(),
2549        )
2550        .await
2551        .unwrap();
2552        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2553            .await;
2554        tree.flush_fs_events(&cx).await;
2555        cx.read(|cx| {
2556            let tree = tree.read(cx);
2557            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2558            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2559            assert_eq!(tracked.is_ignored, false);
2560            assert_eq!(ignored.is_ignored, true);
2561        });
2562
2563        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2564        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2565        tree.flush_fs_events(&cx).await;
2566        cx.read(|cx| {
2567            let tree = tree.read(cx);
2568            let dot_git = tree.entry_for_path(".git").unwrap();
2569            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2570            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2571            assert_eq!(tracked.is_ignored, false);
2572            assert_eq!(ignored.is_ignored, true);
2573            assert_eq!(dot_git.is_ignored, true);
2574        });
2575    }
2576
2577    #[gpui::test(iterations = 100)]
2578    fn test_random(mut rng: StdRng) {
2579        let operations = env::var("OPERATIONS")
2580            .map(|o| o.parse().unwrap())
2581            .unwrap_or(40);
2582        let initial_entries = env::var("INITIAL_ENTRIES")
2583            .map(|o| o.parse().unwrap())
2584            .unwrap_or(20);
2585
2586        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2587        for _ in 0..initial_entries {
2588            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2589        }
2590        log::info!("Generated initial tree");
2591
2592        let (notify_tx, _notify_rx) = mpsc::unbounded();
2593        let fs = Arc::new(RealFs);
2594        let next_entry_id = Arc::new(AtomicUsize::new(0));
2595        let mut initial_snapshot = LocalSnapshot {
2596            abs_path: root_dir.path().into(),
2597            scan_id: 0,
2598            removed_entry_ids: Default::default(),
2599            ignores: Default::default(),
2600            next_entry_id: next_entry_id.clone(),
2601            snapshot: Snapshot {
2602                id: WorktreeId::from_usize(0),
2603                entries_by_path: Default::default(),
2604                entries_by_id: Default::default(),
2605                root_name: Default::default(),
2606                root_char_bag: Default::default(),
2607            },
2608        };
2609        initial_snapshot.insert_entry(
2610            Entry::new(
2611                Path::new("").into(),
2612                &smol::block_on(fs.metadata(root_dir.path()))
2613                    .unwrap()
2614                    .unwrap(),
2615                &next_entry_id,
2616                Default::default(),
2617            ),
2618            fs.as_ref(),
2619        );
2620        let mut scanner = BackgroundScanner::new(
2621            Arc::new(Mutex::new(initial_snapshot.clone())),
2622            notify_tx,
2623            fs.clone(),
2624            Arc::new(gpui::executor::Background::new()),
2625        );
2626        smol::block_on(scanner.scan_dirs()).unwrap();
2627        scanner.snapshot().check_invariants();
2628
2629        let mut events = Vec::new();
2630        let mut snapshots = Vec::new();
2631        let mut mutations_len = operations;
2632        while mutations_len > 1 {
2633            if !events.is_empty() && rng.gen_bool(0.4) {
2634                let len = rng.gen_range(0..=events.len());
2635                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
2636                log::info!("Delivering events: {:#?}", to_deliver);
2637                smol::block_on(scanner.process_events(to_deliver));
2638                scanner.snapshot().check_invariants();
2639            } else {
2640                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
2641                mutations_len -= 1;
2642            }
2643
2644            if rng.gen_bool(0.2) {
2645                snapshots.push(scanner.snapshot());
2646            }
2647        }
2648        log::info!("Quiescing: {:#?}", events);
2649        smol::block_on(scanner.process_events(events));
2650        scanner.snapshot().check_invariants();
2651
2652        let (notify_tx, _notify_rx) = mpsc::unbounded();
2653        let mut new_scanner = BackgroundScanner::new(
2654            Arc::new(Mutex::new(initial_snapshot)),
2655            notify_tx,
2656            scanner.fs.clone(),
2657            scanner.executor.clone(),
2658        );
2659        smol::block_on(new_scanner.scan_dirs()).unwrap();
2660        assert_eq!(
2661            scanner.snapshot().to_vec(true),
2662            new_scanner.snapshot().to_vec(true)
2663        );
2664
2665        for mut prev_snapshot in snapshots {
2666            let include_ignored = rng.gen::<bool>();
2667            if !include_ignored {
2668                let mut entries_by_path_edits = Vec::new();
2669                let mut entries_by_id_edits = Vec::new();
2670                for entry in prev_snapshot
2671                    .entries_by_id
2672                    .cursor::<()>()
2673                    .filter(|e| e.is_ignored)
2674                {
2675                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
2676                    entries_by_id_edits.push(Edit::Remove(entry.id));
2677                }
2678
2679                prev_snapshot
2680                    .entries_by_path
2681                    .edit(entries_by_path_edits, &());
2682                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
2683            }
2684
2685            let update = scanner
2686                .snapshot()
2687                .build_update(&prev_snapshot, 0, 0, include_ignored);
2688            prev_snapshot.apply_remote_update(update).unwrap();
2689            assert_eq!(
2690                prev_snapshot.to_vec(true),
2691                scanner.snapshot().to_vec(include_ignored)
2692            );
2693        }
2694    }
2695
2696    fn randomly_mutate_tree(
2697        root_path: &Path,
2698        insertion_probability: f64,
2699        rng: &mut impl Rng,
2700    ) -> Result<Vec<fsevent::Event>> {
2701        let root_path = root_path.canonicalize().unwrap();
2702        let (dirs, files) = read_dir_recursive(root_path.clone());
2703
2704        let mut events = Vec::new();
2705        let mut record_event = |path: PathBuf| {
2706            events.push(fsevent::Event {
2707                event_id: SystemTime::now()
2708                    .duration_since(UNIX_EPOCH)
2709                    .unwrap()
2710                    .as_secs(),
2711                flags: fsevent::StreamFlags::empty(),
2712                path,
2713            });
2714        };
2715
2716        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
2717            let path = dirs.choose(rng).unwrap();
2718            let new_path = path.join(gen_name(rng));
2719
2720            if rng.gen() {
2721                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
2722                std::fs::create_dir(&new_path)?;
2723            } else {
2724                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
2725                std::fs::write(&new_path, "")?;
2726            }
2727            record_event(new_path);
2728        } else if rng.gen_bool(0.05) {
2729            let ignore_dir_path = dirs.choose(rng).unwrap();
2730            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
2731
2732            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
2733            let files_to_ignore = {
2734                let len = rng.gen_range(0..=subfiles.len());
2735                subfiles.choose_multiple(rng, len)
2736            };
2737            let dirs_to_ignore = {
2738                let len = rng.gen_range(0..subdirs.len());
2739                subdirs.choose_multiple(rng, len)
2740            };
2741
2742            let mut ignore_contents = String::new();
2743            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
2744                write!(
2745                    ignore_contents,
2746                    "{}\n",
2747                    path_to_ignore
2748                        .strip_prefix(&ignore_dir_path)?
2749                        .to_str()
2750                        .unwrap()
2751                )
2752                .unwrap();
2753            }
2754            log::info!(
2755                "Creating {:?} with contents:\n{}",
2756                ignore_path.strip_prefix(&root_path)?,
2757                ignore_contents
2758            );
2759            std::fs::write(&ignore_path, ignore_contents).unwrap();
2760            record_event(ignore_path);
2761        } else {
2762            let old_path = {
2763                let file_path = files.choose(rng);
2764                let dir_path = dirs[1..].choose(rng);
2765                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
2766            };
2767
2768            let is_rename = rng.gen();
2769            if is_rename {
2770                let new_path_parent = dirs
2771                    .iter()
2772                    .filter(|d| !d.starts_with(old_path))
2773                    .choose(rng)
2774                    .unwrap();
2775
2776                let overwrite_existing_dir =
2777                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
2778                let new_path = if overwrite_existing_dir {
2779                    std::fs::remove_dir_all(&new_path_parent).ok();
2780                    new_path_parent.to_path_buf()
2781                } else {
2782                    new_path_parent.join(gen_name(rng))
2783                };
2784
2785                log::info!(
2786                    "Renaming {:?} to {}{:?}",
2787                    old_path.strip_prefix(&root_path)?,
2788                    if overwrite_existing_dir {
2789                        "overwrite "
2790                    } else {
2791                        ""
2792                    },
2793                    new_path.strip_prefix(&root_path)?
2794                );
2795                std::fs::rename(&old_path, &new_path)?;
2796                record_event(old_path.clone());
2797                record_event(new_path);
2798            } else if old_path.is_dir() {
2799                let (dirs, files) = read_dir_recursive(old_path.clone());
2800
2801                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
2802                std::fs::remove_dir_all(&old_path).unwrap();
2803                for file in files {
2804                    record_event(file);
2805                }
2806                for dir in dirs {
2807                    record_event(dir);
2808                }
2809            } else {
2810                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
2811                std::fs::remove_file(old_path).unwrap();
2812                record_event(old_path.clone());
2813            }
2814        }
2815
2816        Ok(events)
2817    }
2818
2819    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
2820        let child_entries = std::fs::read_dir(&path).unwrap();
2821        let mut dirs = vec![path];
2822        let mut files = Vec::new();
2823        for child_entry in child_entries {
2824            let child_path = child_entry.unwrap().path();
2825            if child_path.is_dir() {
2826                let (child_dirs, child_files) = read_dir_recursive(child_path);
2827                dirs.extend(child_dirs);
2828                files.extend(child_files);
2829            } else {
2830                files.push(child_path);
2831            }
2832        }
2833        (dirs, files)
2834    }
2835
2836    fn gen_name(rng: &mut impl Rng) -> String {
2837        (0..6)
2838            .map(|_| rng.sample(rand::distributions::Alphanumeric))
2839            .map(char::from)
2840            .collect()
2841    }
2842
2843    impl LocalSnapshot {
2844        fn check_invariants(&self) {
2845            let mut files = self.files(true, 0);
2846            let mut visible_files = self.files(false, 0);
2847            for entry in self.entries_by_path.cursor::<()>() {
2848                if entry.is_file() {
2849                    assert_eq!(files.next().unwrap().inode, entry.inode);
2850                    if !entry.is_ignored {
2851                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2852                    }
2853                }
2854            }
2855            assert!(files.next().is_none());
2856            assert!(visible_files.next().is_none());
2857
2858            let mut bfs_paths = Vec::new();
2859            let mut stack = vec![Path::new("")];
2860            while let Some(path) = stack.pop() {
2861                bfs_paths.push(path);
2862                let ix = stack.len();
2863                for child_entry in self.child_entries(path) {
2864                    stack.insert(ix, &child_entry.path);
2865                }
2866            }
2867
2868            let dfs_paths = self
2869                .entries_by_path
2870                .cursor::<()>()
2871                .map(|e| e.path.as_ref())
2872                .collect::<Vec<_>>();
2873            assert_eq!(bfs_paths, dfs_paths);
2874
2875            for (ignore_parent_path, _) in &self.ignores {
2876                assert!(self.entry_for_path(ignore_parent_path).is_some());
2877                assert!(self
2878                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2879                    .is_some());
2880            }
2881        }
2882
2883        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2884            let mut paths = Vec::new();
2885            for entry in self.entries_by_path.cursor::<()>() {
2886                if include_ignored || !entry.is_ignored {
2887                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2888                }
2889            }
2890            paths.sort_by(|a, b| a.0.cmp(&b.0));
2891            paths
2892        }
2893    }
2894}