worktree.rs

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