worktree.rs

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