worktree.rs

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