worktree.rs

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