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