worktree.rs

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