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