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);
1459        }
1460        self.inc_extension_count(&entry.path);
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);
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);
1512        }
1513    }
1514
1515    fn inc_extension_count(&mut self, path: &Path) {
1516        if let Some(extension) = path.extension() {
1517            if let Some(count) = self.extension_counts.get_mut(extension) {
1518                *count += 1;
1519            } else {
1520                self.extension_counts.insert(extension.into(), 1);
1521            }
1522        }
1523    }
1524
1525    fn dec_extension_count(&mut self, path: &Path) {
1526        if let Some(extension) = path.extension() {
1527            if let Some(count) = self.extension_counts.get_mut(extension) {
1528                *count -= 1;
1529            }
1530        }
1531    }
1532
1533    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1534        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1535            entry.id = removed_entry_id;
1536        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1537            entry.id = existing_entry.id;
1538        }
1539    }
1540
1541    fn remove_path(&mut self, path: &Path) {
1542        let mut new_entries;
1543        let removed_entries;
1544        {
1545            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1546            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1547            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1548            new_entries.push_tree(cursor.suffix(&()), &());
1549        }
1550        self.entries_by_path = new_entries;
1551
1552        let mut entries_by_id_edits = Vec::new();
1553        for entry in removed_entries.cursor::<()>() {
1554            let removed_entry_id = self
1555                .removed_entry_ids
1556                .entry(entry.inode)
1557                .or_insert(entry.id);
1558            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1559            entries_by_id_edits.push(Edit::Remove(entry.id));
1560            self.dec_extension_count(&entry.path);
1561        }
1562        self.entries_by_id.edit(entries_by_id_edits, &());
1563
1564        if path.file_name() == Some(&GITIGNORE) {
1565            if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1566                *scan_id = self.snapshot.scan_id;
1567            }
1568        }
1569    }
1570
1571    fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1572        let mut new_ignores = Vec::new();
1573        for ancestor in path.ancestors().skip(1) {
1574            if let Some((ignore, _)) = self.ignores.get(ancestor) {
1575                new_ignores.push((ancestor, Some(ignore.clone())));
1576            } else {
1577                new_ignores.push((ancestor, None));
1578            }
1579        }
1580
1581        let mut ignore_stack = IgnoreStack::none();
1582        for (parent_path, ignore) in new_ignores.into_iter().rev() {
1583            if ignore_stack.is_path_ignored(&parent_path, true) {
1584                ignore_stack = IgnoreStack::all();
1585                break;
1586            } else if let Some(ignore) = ignore {
1587                ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1588            }
1589        }
1590
1591        if ignore_stack.is_path_ignored(path, is_dir) {
1592            ignore_stack = IgnoreStack::all();
1593        }
1594
1595        ignore_stack
1596    }
1597}
1598
1599fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1600    let contents = smol::block_on(fs.load(&abs_path))?;
1601    let parent = abs_path.parent().unwrap_or(Path::new("/"));
1602    let mut builder = GitignoreBuilder::new(parent);
1603    for line in contents.lines() {
1604        builder.add_line(Some(abs_path.into()), line)?;
1605    }
1606    Ok(builder.build()?)
1607}
1608
1609impl WorktreeId {
1610    pub fn from_usize(handle_id: usize) -> Self {
1611        Self(handle_id)
1612    }
1613
1614    pub(crate) fn from_proto(id: u64) -> Self {
1615        Self(id as usize)
1616    }
1617
1618    pub fn to_proto(&self) -> u64 {
1619        self.0 as u64
1620    }
1621
1622    pub fn to_usize(&self) -> usize {
1623        self.0
1624    }
1625}
1626
1627impl fmt::Display for WorktreeId {
1628    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629        self.0.fmt(f)
1630    }
1631}
1632
1633impl Deref for Worktree {
1634    type Target = Snapshot;
1635
1636    fn deref(&self) -> &Self::Target {
1637        match self {
1638            Worktree::Local(worktree) => &worktree.snapshot,
1639            Worktree::Remote(worktree) => &worktree.snapshot,
1640        }
1641    }
1642}
1643
1644impl Deref for LocalWorktree {
1645    type Target = LocalSnapshot;
1646
1647    fn deref(&self) -> &Self::Target {
1648        &self.snapshot
1649    }
1650}
1651
1652impl Deref for RemoteWorktree {
1653    type Target = Snapshot;
1654
1655    fn deref(&self) -> &Self::Target {
1656        &self.snapshot
1657    }
1658}
1659
1660impl fmt::Debug for LocalWorktree {
1661    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1662        self.snapshot.fmt(f)
1663    }
1664}
1665
1666impl fmt::Debug for Snapshot {
1667    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1668        struct EntriesById<'a>(&'a SumTree<PathEntry>);
1669        struct EntriesByPath<'a>(&'a SumTree<Entry>);
1670
1671        impl<'a> fmt::Debug for EntriesByPath<'a> {
1672            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1673                f.debug_map()
1674                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1675                    .finish()
1676            }
1677        }
1678
1679        impl<'a> fmt::Debug for EntriesById<'a> {
1680            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1681                f.debug_list().entries(self.0.iter()).finish()
1682            }
1683        }
1684
1685        f.debug_struct("Snapshot")
1686            .field("id", &self.id)
1687            .field("root_name", &self.root_name)
1688            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1689            .field("entries_by_id", &EntriesById(&self.entries_by_id))
1690            .finish()
1691    }
1692}
1693
1694#[derive(Clone, PartialEq)]
1695pub struct File {
1696    pub worktree: ModelHandle<Worktree>,
1697    pub path: Arc<Path>,
1698    pub mtime: SystemTime,
1699    pub(crate) entry_id: Option<ProjectEntryId>,
1700    pub(crate) is_local: bool,
1701}
1702
1703impl language::File for File {
1704    fn as_local(&self) -> Option<&dyn language::LocalFile> {
1705        if self.is_local {
1706            Some(self)
1707        } else {
1708            None
1709        }
1710    }
1711
1712    fn mtime(&self) -> SystemTime {
1713        self.mtime
1714    }
1715
1716    fn path(&self) -> &Arc<Path> {
1717        &self.path
1718    }
1719
1720    fn full_path(&self, cx: &AppContext) -> PathBuf {
1721        let mut full_path = PathBuf::new();
1722        full_path.push(self.worktree.read(cx).root_name());
1723        if self.path.components().next().is_some() {
1724            full_path.push(&self.path);
1725        }
1726        full_path
1727    }
1728
1729    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1730    /// of its worktree, then this method will return the name of the worktree itself.
1731    fn file_name(&self, cx: &AppContext) -> OsString {
1732        self.path
1733            .file_name()
1734            .map(|name| name.into())
1735            .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1736    }
1737
1738    fn is_deleted(&self) -> bool {
1739        self.entry_id.is_none()
1740    }
1741
1742    fn save(
1743        &self,
1744        buffer_id: u64,
1745        text: Rope,
1746        version: clock::Global,
1747        cx: &mut MutableAppContext,
1748    ) -> Task<Result<(clock::Global, String, SystemTime)>> {
1749        self.worktree.update(cx, |worktree, cx| match worktree {
1750            Worktree::Local(worktree) => {
1751                let rpc = worktree.client.clone();
1752                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1753                let fingerprint = text.fingerprint();
1754                let save = worktree.write_file(self.path.clone(), text, cx);
1755                cx.background().spawn(async move {
1756                    let entry = save.await?;
1757                    if let Some(project_id) = project_id {
1758                        rpc.send(proto::BufferSaved {
1759                            project_id,
1760                            buffer_id,
1761                            version: serialize_version(&version),
1762                            mtime: Some(entry.mtime.into()),
1763                            fingerprint: fingerprint.clone(),
1764                        })?;
1765                    }
1766                    Ok((version, fingerprint, entry.mtime))
1767                })
1768            }
1769            Worktree::Remote(worktree) => {
1770                let rpc = worktree.client.clone();
1771                let project_id = worktree.project_id;
1772                cx.foreground().spawn(async move {
1773                    let response = rpc
1774                        .request(proto::SaveBuffer {
1775                            project_id,
1776                            buffer_id,
1777                            version: serialize_version(&version),
1778                        })
1779                        .await?;
1780                    let version = deserialize_version(response.version);
1781                    let mtime = response
1782                        .mtime
1783                        .ok_or_else(|| anyhow!("missing mtime"))?
1784                        .into();
1785                    Ok((version, response.fingerprint, mtime))
1786                })
1787            }
1788        })
1789    }
1790
1791    fn as_any(&self) -> &dyn Any {
1792        self
1793    }
1794
1795    fn to_proto(&self) -> rpc::proto::File {
1796        rpc::proto::File {
1797            worktree_id: self.worktree.id() as u64,
1798            entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1799            path: self.path.to_string_lossy().into(),
1800            mtime: Some(self.mtime.into()),
1801        }
1802    }
1803}
1804
1805impl language::LocalFile for File {
1806    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1807        self.worktree
1808            .read(cx)
1809            .as_local()
1810            .unwrap()
1811            .abs_path
1812            .join(&self.path)
1813    }
1814
1815    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1816        let worktree = self.worktree.read(cx).as_local().unwrap();
1817        let abs_path = worktree.absolutize(&self.path);
1818        let fs = worktree.fs.clone();
1819        cx.background()
1820            .spawn(async move { fs.load(&abs_path).await })
1821    }
1822
1823    fn buffer_reloaded(
1824        &self,
1825        buffer_id: u64,
1826        version: &clock::Global,
1827        fingerprint: String,
1828        mtime: SystemTime,
1829        cx: &mut MutableAppContext,
1830    ) {
1831        let worktree = self.worktree.read(cx).as_local().unwrap();
1832        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1833            worktree
1834                .client
1835                .send(proto::BufferReloaded {
1836                    project_id,
1837                    buffer_id,
1838                    version: serialize_version(&version),
1839                    mtime: Some(mtime.into()),
1840                    fingerprint,
1841                })
1842                .log_err();
1843        }
1844    }
1845}
1846
1847impl File {
1848    pub fn from_proto(
1849        proto: rpc::proto::File,
1850        worktree: ModelHandle<Worktree>,
1851        cx: &AppContext,
1852    ) -> Result<Self> {
1853        let worktree_id = worktree
1854            .read(cx)
1855            .as_remote()
1856            .ok_or_else(|| anyhow!("not remote"))?
1857            .id();
1858
1859        if worktree_id.to_proto() != proto.worktree_id {
1860            return Err(anyhow!("worktree id does not match file"));
1861        }
1862
1863        Ok(Self {
1864            worktree,
1865            path: Path::new(&proto.path).into(),
1866            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1867            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1868            is_local: false,
1869        })
1870    }
1871
1872    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1873        file.and_then(|f| f.as_any().downcast_ref())
1874    }
1875
1876    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1877        self.worktree.read(cx).id()
1878    }
1879
1880    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1881        self.entry_id
1882    }
1883}
1884
1885#[derive(Clone, Debug, PartialEq, Eq)]
1886pub struct Entry {
1887    pub id: ProjectEntryId,
1888    pub kind: EntryKind,
1889    pub path: Arc<Path>,
1890    pub inode: u64,
1891    pub mtime: SystemTime,
1892    pub is_symlink: bool,
1893    pub is_ignored: bool,
1894}
1895
1896#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1897pub enum EntryKind {
1898    PendingDir,
1899    Dir,
1900    File(CharBag),
1901}
1902
1903impl Entry {
1904    fn new(
1905        path: Arc<Path>,
1906        metadata: &fs::Metadata,
1907        next_entry_id: &AtomicUsize,
1908        root_char_bag: CharBag,
1909    ) -> Self {
1910        Self {
1911            id: ProjectEntryId::new(next_entry_id),
1912            kind: if metadata.is_dir {
1913                EntryKind::PendingDir
1914            } else {
1915                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1916            },
1917            path,
1918            inode: metadata.inode,
1919            mtime: metadata.mtime,
1920            is_symlink: metadata.is_symlink,
1921            is_ignored: false,
1922        }
1923    }
1924
1925    pub fn is_dir(&self) -> bool {
1926        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1927    }
1928
1929    pub fn is_file(&self) -> bool {
1930        matches!(self.kind, EntryKind::File(_))
1931    }
1932}
1933
1934impl sum_tree::Item for Entry {
1935    type Summary = EntrySummary;
1936
1937    fn summary(&self) -> Self::Summary {
1938        let visible_count = if self.is_ignored { 0 } else { 1 };
1939        let file_count;
1940        let visible_file_count;
1941        if self.is_file() {
1942            file_count = 1;
1943            visible_file_count = visible_count;
1944        } else {
1945            file_count = 0;
1946            visible_file_count = 0;
1947        }
1948
1949        EntrySummary {
1950            max_path: self.path.clone(),
1951            count: 1,
1952            visible_count,
1953            file_count,
1954            visible_file_count,
1955        }
1956    }
1957}
1958
1959impl sum_tree::KeyedItem for Entry {
1960    type Key = PathKey;
1961
1962    fn key(&self) -> Self::Key {
1963        PathKey(self.path.clone())
1964    }
1965}
1966
1967#[derive(Clone, Debug)]
1968pub struct EntrySummary {
1969    max_path: Arc<Path>,
1970    count: usize,
1971    visible_count: usize,
1972    file_count: usize,
1973    visible_file_count: usize,
1974}
1975
1976impl Default for EntrySummary {
1977    fn default() -> Self {
1978        Self {
1979            max_path: Arc::from(Path::new("")),
1980            count: 0,
1981            visible_count: 0,
1982            file_count: 0,
1983            visible_file_count: 0,
1984        }
1985    }
1986}
1987
1988impl sum_tree::Summary for EntrySummary {
1989    type Context = ();
1990
1991    fn add_summary(&mut self, rhs: &Self, _: &()) {
1992        self.max_path = rhs.max_path.clone();
1993        self.count += rhs.count;
1994        self.visible_count += rhs.visible_count;
1995        self.file_count += rhs.file_count;
1996        self.visible_file_count += rhs.visible_file_count;
1997    }
1998}
1999
2000#[derive(Clone, Debug)]
2001struct PathEntry {
2002    id: ProjectEntryId,
2003    path: Arc<Path>,
2004    is_ignored: bool,
2005    scan_id: usize,
2006}
2007
2008impl sum_tree::Item for PathEntry {
2009    type Summary = PathEntrySummary;
2010
2011    fn summary(&self) -> Self::Summary {
2012        PathEntrySummary { max_id: self.id }
2013    }
2014}
2015
2016impl sum_tree::KeyedItem for PathEntry {
2017    type Key = ProjectEntryId;
2018
2019    fn key(&self) -> Self::Key {
2020        self.id
2021    }
2022}
2023
2024#[derive(Clone, Debug, Default)]
2025struct PathEntrySummary {
2026    max_id: ProjectEntryId,
2027}
2028
2029impl sum_tree::Summary for PathEntrySummary {
2030    type Context = ();
2031
2032    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2033        self.max_id = summary.max_id;
2034    }
2035}
2036
2037impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2038    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2039        *self = summary.max_id;
2040    }
2041}
2042
2043#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2044pub struct PathKey(Arc<Path>);
2045
2046impl Default for PathKey {
2047    fn default() -> Self {
2048        Self(Path::new("").into())
2049    }
2050}
2051
2052impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2053    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2054        self.0 = summary.max_path.clone();
2055    }
2056}
2057
2058struct BackgroundScanner {
2059    fs: Arc<dyn Fs>,
2060    snapshot: Arc<Mutex<LocalSnapshot>>,
2061    notify: UnboundedSender<ScanState>,
2062    executor: Arc<executor::Background>,
2063}
2064
2065impl BackgroundScanner {
2066    fn new(
2067        snapshot: Arc<Mutex<LocalSnapshot>>,
2068        notify: UnboundedSender<ScanState>,
2069        fs: Arc<dyn Fs>,
2070        executor: Arc<executor::Background>,
2071    ) -> Self {
2072        Self {
2073            fs,
2074            snapshot,
2075            notify,
2076            executor,
2077        }
2078    }
2079
2080    fn abs_path(&self) -> Arc<Path> {
2081        self.snapshot.lock().abs_path.clone()
2082    }
2083
2084    fn snapshot(&self) -> LocalSnapshot {
2085        self.snapshot.lock().clone()
2086    }
2087
2088    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2089        if self.notify.unbounded_send(ScanState::Scanning).is_err() {
2090            return;
2091        }
2092
2093        if let Err(err) = self.scan_dirs().await {
2094            if self
2095                .notify
2096                .unbounded_send(ScanState::Err(Arc::new(err)))
2097                .is_err()
2098            {
2099                return;
2100            }
2101        }
2102
2103        if self.notify.unbounded_send(ScanState::Idle).is_err() {
2104            return;
2105        }
2106
2107        futures::pin_mut!(events_rx);
2108        while let Some(events) = events_rx.next().await {
2109            if self.notify.unbounded_send(ScanState::Scanning).is_err() {
2110                break;
2111            }
2112
2113            if !self.process_events(events).await {
2114                break;
2115            }
2116
2117            if self.notify.unbounded_send(ScanState::Idle).is_err() {
2118                break;
2119            }
2120        }
2121    }
2122
2123    async fn scan_dirs(&mut self) -> Result<()> {
2124        let root_char_bag;
2125        let next_entry_id;
2126        let is_dir;
2127        {
2128            let snapshot = self.snapshot.lock();
2129            root_char_bag = snapshot.root_char_bag;
2130            next_entry_id = snapshot.next_entry_id.clone();
2131            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
2132        };
2133
2134        if is_dir {
2135            let path: Arc<Path> = Arc::from(Path::new(""));
2136            let abs_path = self.abs_path();
2137            let (tx, rx) = channel::unbounded();
2138            self.executor
2139                .block(tx.send(ScanJob {
2140                    abs_path: abs_path.to_path_buf(),
2141                    path,
2142                    ignore_stack: IgnoreStack::none(),
2143                    scan_queue: tx.clone(),
2144                }))
2145                .unwrap();
2146            drop(tx);
2147
2148            self.executor
2149                .scoped(|scope| {
2150                    for _ in 0..self.executor.num_cpus() {
2151                        scope.spawn(async {
2152                            while let Ok(job) = rx.recv().await {
2153                                if let Err(err) = self
2154                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2155                                    .await
2156                                {
2157                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
2158                                }
2159                            }
2160                        });
2161                    }
2162                })
2163                .await;
2164        }
2165
2166        Ok(())
2167    }
2168
2169    async fn scan_dir(
2170        &self,
2171        root_char_bag: CharBag,
2172        next_entry_id: Arc<AtomicUsize>,
2173        job: &ScanJob,
2174    ) -> Result<()> {
2175        let mut new_entries: Vec<Entry> = Vec::new();
2176        let mut new_jobs: Vec<ScanJob> = Vec::new();
2177        let mut ignore_stack = job.ignore_stack.clone();
2178        let mut new_ignore = None;
2179
2180        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2181        while let Some(child_abs_path) = child_paths.next().await {
2182            let child_abs_path = match child_abs_path {
2183                Ok(child_abs_path) => child_abs_path,
2184                Err(error) => {
2185                    log::error!("error processing entry {:?}", error);
2186                    continue;
2187                }
2188            };
2189            let child_name = child_abs_path.file_name().unwrap();
2190            let child_path: Arc<Path> = job.path.join(child_name).into();
2191            let child_metadata = match self.fs.metadata(&child_abs_path).await {
2192                Ok(Some(metadata)) => metadata,
2193                Ok(None) => continue,
2194                Err(err) => {
2195                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
2196                    continue;
2197                }
2198            };
2199
2200            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2201            if child_name == *GITIGNORE {
2202                match build_gitignore(&child_abs_path, self.fs.as_ref()) {
2203                    Ok(ignore) => {
2204                        let ignore = Arc::new(ignore);
2205                        ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2206                        new_ignore = Some(ignore);
2207                    }
2208                    Err(error) => {
2209                        log::error!(
2210                            "error loading .gitignore file {:?} - {:?}",
2211                            child_name,
2212                            error
2213                        );
2214                    }
2215                }
2216
2217                // Update ignore status of any child entries we've already processed to reflect the
2218                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2219                // there should rarely be too numerous. Update the ignore stack associated with any
2220                // new jobs as well.
2221                let mut new_jobs = new_jobs.iter_mut();
2222                for entry in &mut new_entries {
2223                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2224                    if entry.is_dir() {
2225                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2226                            IgnoreStack::all()
2227                        } else {
2228                            ignore_stack.clone()
2229                        };
2230                    }
2231                }
2232            }
2233
2234            let mut child_entry = Entry::new(
2235                child_path.clone(),
2236                &child_metadata,
2237                &next_entry_id,
2238                root_char_bag,
2239            );
2240
2241            if child_metadata.is_dir {
2242                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2243                child_entry.is_ignored = is_ignored;
2244                new_entries.push(child_entry);
2245                new_jobs.push(ScanJob {
2246                    abs_path: child_abs_path,
2247                    path: child_path,
2248                    ignore_stack: if is_ignored {
2249                        IgnoreStack::all()
2250                    } else {
2251                        ignore_stack.clone()
2252                    },
2253                    scan_queue: job.scan_queue.clone(),
2254                });
2255            } else {
2256                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2257                new_entries.push(child_entry);
2258            };
2259        }
2260
2261        self.snapshot
2262            .lock()
2263            .populate_dir(job.path.clone(), new_entries, new_ignore);
2264        for new_job in new_jobs {
2265            job.scan_queue.send(new_job).await.unwrap();
2266        }
2267
2268        Ok(())
2269    }
2270
2271    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2272        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2273        events.dedup_by(|a, b| a.path.starts_with(&b.path));
2274
2275        let root_char_bag;
2276        let root_abs_path;
2277        let next_entry_id;
2278        {
2279            let snapshot = self.snapshot.lock();
2280            root_char_bag = snapshot.root_char_bag;
2281            root_abs_path = snapshot.abs_path.clone();
2282            next_entry_id = snapshot.next_entry_id.clone();
2283        }
2284
2285        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&root_abs_path).await {
2286            abs_path
2287        } else {
2288            return false;
2289        };
2290        let metadata = futures::future::join_all(
2291            events
2292                .iter()
2293                .map(|event| self.fs.metadata(&event.path))
2294                .collect::<Vec<_>>(),
2295        )
2296        .await;
2297
2298        // Hold the snapshot lock while clearing and re-inserting the root entries
2299        // for each event. This way, the snapshot is not observable to the foreground
2300        // thread while this operation is in-progress.
2301        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2302        {
2303            let mut snapshot = self.snapshot.lock();
2304            snapshot.scan_id += 1;
2305            for event in &events {
2306                if let Ok(path) = event.path.strip_prefix(&root_abs_path) {
2307                    snapshot.remove_path(&path);
2308                }
2309            }
2310
2311            for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2312                let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2313                    Ok(path) => Arc::from(path.to_path_buf()),
2314                    Err(_) => {
2315                        log::error!(
2316                            "unexpected event {:?} for root path {:?}",
2317                            event.path,
2318                            root_abs_path
2319                        );
2320                        continue;
2321                    }
2322                };
2323
2324                match metadata {
2325                    Ok(Some(metadata)) => {
2326                        let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2327                        let mut fs_entry = Entry::new(
2328                            path.clone(),
2329                            &metadata,
2330                            snapshot.next_entry_id.as_ref(),
2331                            snapshot.root_char_bag,
2332                        );
2333                        fs_entry.is_ignored = ignore_stack.is_all();
2334                        snapshot.insert_entry(fs_entry, self.fs.as_ref());
2335                        if metadata.is_dir {
2336                            self.executor
2337                                .block(scan_queue_tx.send(ScanJob {
2338                                    abs_path: event.path,
2339                                    path,
2340                                    ignore_stack,
2341                                    scan_queue: scan_queue_tx.clone(),
2342                                }))
2343                                .unwrap();
2344                        }
2345                    }
2346                    Ok(None) => {}
2347                    Err(err) => {
2348                        // TODO - create a special 'error' entry in the entries tree to mark this
2349                        log::error!("error reading file on event {:?}", err);
2350                    }
2351                }
2352            }
2353            drop(scan_queue_tx);
2354        }
2355
2356        // Scan any directories that were created as part of this event batch.
2357        self.executor
2358            .scoped(|scope| {
2359                for _ in 0..self.executor.num_cpus() {
2360                    scope.spawn(async {
2361                        while let Ok(job) = scan_queue_rx.recv().await {
2362                            if let Err(err) = self
2363                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2364                                .await
2365                            {
2366                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2367                            }
2368                        }
2369                    });
2370                }
2371            })
2372            .await;
2373
2374        // Attempt to detect renames only over a single batch of file-system events.
2375        self.snapshot.lock().removed_entry_ids.clear();
2376
2377        self.update_ignore_statuses().await;
2378        true
2379    }
2380
2381    async fn update_ignore_statuses(&self) {
2382        let mut snapshot = self.snapshot();
2383
2384        let mut ignores_to_update = Vec::new();
2385        let mut ignores_to_delete = Vec::new();
2386        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2387            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2388                ignores_to_update.push(parent_path.clone());
2389            }
2390
2391            let ignore_path = parent_path.join(&*GITIGNORE);
2392            if snapshot.entry_for_path(ignore_path).is_none() {
2393                ignores_to_delete.push(parent_path.clone());
2394            }
2395        }
2396
2397        for parent_path in ignores_to_delete {
2398            snapshot.ignores.remove(&parent_path);
2399            self.snapshot.lock().ignores.remove(&parent_path);
2400        }
2401
2402        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2403        ignores_to_update.sort_unstable();
2404        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2405        while let Some(parent_path) = ignores_to_update.next() {
2406            while ignores_to_update
2407                .peek()
2408                .map_or(false, |p| p.starts_with(&parent_path))
2409            {
2410                ignores_to_update.next().unwrap();
2411            }
2412
2413            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2414            ignore_queue_tx
2415                .send(UpdateIgnoreStatusJob {
2416                    path: parent_path,
2417                    ignore_stack,
2418                    ignore_queue: ignore_queue_tx.clone(),
2419                })
2420                .await
2421                .unwrap();
2422        }
2423        drop(ignore_queue_tx);
2424
2425        self.executor
2426            .scoped(|scope| {
2427                for _ in 0..self.executor.num_cpus() {
2428                    scope.spawn(async {
2429                        while let Ok(job) = ignore_queue_rx.recv().await {
2430                            self.update_ignore_status(job, &snapshot).await;
2431                        }
2432                    });
2433                }
2434            })
2435            .await;
2436    }
2437
2438    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2439        let mut ignore_stack = job.ignore_stack;
2440        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2441            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2442        }
2443
2444        let mut entries_by_id_edits = Vec::new();
2445        let mut entries_by_path_edits = Vec::new();
2446        for mut entry in snapshot.child_entries(&job.path).cloned() {
2447            let was_ignored = entry.is_ignored;
2448            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2449            if entry.is_dir() {
2450                let child_ignore_stack = if entry.is_ignored {
2451                    IgnoreStack::all()
2452                } else {
2453                    ignore_stack.clone()
2454                };
2455                job.ignore_queue
2456                    .send(UpdateIgnoreStatusJob {
2457                        path: entry.path.clone(),
2458                        ignore_stack: child_ignore_stack,
2459                        ignore_queue: job.ignore_queue.clone(),
2460                    })
2461                    .await
2462                    .unwrap();
2463            }
2464
2465            if entry.is_ignored != was_ignored {
2466                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2467                path_entry.scan_id = snapshot.scan_id;
2468                path_entry.is_ignored = entry.is_ignored;
2469                entries_by_id_edits.push(Edit::Insert(path_entry));
2470                entries_by_path_edits.push(Edit::Insert(entry));
2471            }
2472        }
2473
2474        let mut snapshot = self.snapshot.lock();
2475        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2476        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2477    }
2478}
2479
2480fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2481    let mut result = root_char_bag;
2482    result.extend(
2483        path.to_string_lossy()
2484            .chars()
2485            .map(|c| c.to_ascii_lowercase()),
2486    );
2487    result
2488}
2489
2490struct ScanJob {
2491    abs_path: PathBuf,
2492    path: Arc<Path>,
2493    ignore_stack: Arc<IgnoreStack>,
2494    scan_queue: Sender<ScanJob>,
2495}
2496
2497struct UpdateIgnoreStatusJob {
2498    path: Arc<Path>,
2499    ignore_stack: Arc<IgnoreStack>,
2500    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2501}
2502
2503pub trait WorktreeHandle {
2504    #[cfg(any(test, feature = "test-support"))]
2505    fn flush_fs_events<'a>(
2506        &self,
2507        cx: &'a gpui::TestAppContext,
2508    ) -> futures::future::LocalBoxFuture<'a, ()>;
2509}
2510
2511impl WorktreeHandle for ModelHandle<Worktree> {
2512    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2513    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2514    // extra directory scans, and emit extra scan-state notifications.
2515    //
2516    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2517    // to ensure that all redundant FS events have already been processed.
2518    #[cfg(any(test, feature = "test-support"))]
2519    fn flush_fs_events<'a>(
2520        &self,
2521        cx: &'a gpui::TestAppContext,
2522    ) -> futures::future::LocalBoxFuture<'a, ()> {
2523        use smol::future::FutureExt;
2524
2525        let filename = "fs-event-sentinel";
2526        let tree = self.clone();
2527        let (fs, root_path) = self.read_with(cx, |tree, _| {
2528            let tree = tree.as_local().unwrap();
2529            (tree.fs.clone(), tree.abs_path().clone())
2530        });
2531
2532        async move {
2533            fs.create_file(&root_path.join(filename), Default::default())
2534                .await
2535                .unwrap();
2536            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2537                .await;
2538
2539            fs.remove_file(&root_path.join(filename), Default::default())
2540                .await
2541                .unwrap();
2542            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2543                .await;
2544
2545            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2546                .await;
2547        }
2548        .boxed_local()
2549    }
2550}
2551
2552#[derive(Clone, Debug)]
2553struct TraversalProgress<'a> {
2554    max_path: &'a Path,
2555    count: usize,
2556    visible_count: usize,
2557    file_count: usize,
2558    visible_file_count: usize,
2559}
2560
2561impl<'a> TraversalProgress<'a> {
2562    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2563        match (include_ignored, include_dirs) {
2564            (true, true) => self.count,
2565            (true, false) => self.file_count,
2566            (false, true) => self.visible_count,
2567            (false, false) => self.visible_file_count,
2568        }
2569    }
2570}
2571
2572impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2573    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2574        self.max_path = summary.max_path.as_ref();
2575        self.count += summary.count;
2576        self.visible_count += summary.visible_count;
2577        self.file_count += summary.file_count;
2578        self.visible_file_count += summary.visible_file_count;
2579    }
2580}
2581
2582impl<'a> Default for TraversalProgress<'a> {
2583    fn default() -> Self {
2584        Self {
2585            max_path: Path::new(""),
2586            count: 0,
2587            visible_count: 0,
2588            file_count: 0,
2589            visible_file_count: 0,
2590        }
2591    }
2592}
2593
2594pub struct Traversal<'a> {
2595    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2596    include_ignored: bool,
2597    include_dirs: bool,
2598}
2599
2600impl<'a> Traversal<'a> {
2601    pub fn advance(&mut self) -> bool {
2602        self.advance_to_offset(self.offset() + 1)
2603    }
2604
2605    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2606        self.cursor.seek_forward(
2607            &TraversalTarget::Count {
2608                count: offset,
2609                include_dirs: self.include_dirs,
2610                include_ignored: self.include_ignored,
2611            },
2612            Bias::Right,
2613            &(),
2614        )
2615    }
2616
2617    pub fn advance_to_sibling(&mut self) -> bool {
2618        while let Some(entry) = self.cursor.item() {
2619            self.cursor.seek_forward(
2620                &TraversalTarget::PathSuccessor(&entry.path),
2621                Bias::Left,
2622                &(),
2623            );
2624            if let Some(entry) = self.cursor.item() {
2625                if (self.include_dirs || !entry.is_dir())
2626                    && (self.include_ignored || !entry.is_ignored)
2627                {
2628                    return true;
2629                }
2630            }
2631        }
2632        false
2633    }
2634
2635    pub fn entry(&self) -> Option<&'a Entry> {
2636        self.cursor.item()
2637    }
2638
2639    pub fn offset(&self) -> usize {
2640        self.cursor
2641            .start()
2642            .count(self.include_dirs, self.include_ignored)
2643    }
2644}
2645
2646impl<'a> Iterator for Traversal<'a> {
2647    type Item = &'a Entry;
2648
2649    fn next(&mut self) -> Option<Self::Item> {
2650        if let Some(item) = self.entry() {
2651            self.advance();
2652            Some(item)
2653        } else {
2654            None
2655        }
2656    }
2657}
2658
2659#[derive(Debug)]
2660enum TraversalTarget<'a> {
2661    Path(&'a Path),
2662    PathSuccessor(&'a Path),
2663    Count {
2664        count: usize,
2665        include_ignored: bool,
2666        include_dirs: bool,
2667    },
2668}
2669
2670impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2671    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2672        match self {
2673            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2674            TraversalTarget::PathSuccessor(path) => {
2675                if !cursor_location.max_path.starts_with(path) {
2676                    Ordering::Equal
2677                } else {
2678                    Ordering::Greater
2679                }
2680            }
2681            TraversalTarget::Count {
2682                count,
2683                include_dirs,
2684                include_ignored,
2685            } => Ord::cmp(
2686                count,
2687                &cursor_location.count(*include_dirs, *include_ignored),
2688            ),
2689        }
2690    }
2691}
2692
2693struct ChildEntriesIter<'a> {
2694    parent_path: &'a Path,
2695    traversal: Traversal<'a>,
2696}
2697
2698impl<'a> Iterator for ChildEntriesIter<'a> {
2699    type Item = &'a Entry;
2700
2701    fn next(&mut self) -> Option<Self::Item> {
2702        if let Some(item) = self.traversal.entry() {
2703            if item.path.starts_with(&self.parent_path) {
2704                self.traversal.advance_to_sibling();
2705                return Some(item);
2706            }
2707        }
2708        None
2709    }
2710}
2711
2712impl<'a> From<&'a Entry> for proto::Entry {
2713    fn from(entry: &'a Entry) -> Self {
2714        Self {
2715            id: entry.id.to_proto(),
2716            is_dir: entry.is_dir(),
2717            path: entry.path.as_os_str().as_bytes().to_vec(),
2718            inode: entry.inode,
2719            mtime: Some(entry.mtime.into()),
2720            is_symlink: entry.is_symlink,
2721            is_ignored: entry.is_ignored,
2722        }
2723    }
2724}
2725
2726impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2727    type Error = anyhow::Error;
2728
2729    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2730        if let Some(mtime) = entry.mtime {
2731            let kind = if entry.is_dir {
2732                EntryKind::Dir
2733            } else {
2734                let mut char_bag = root_char_bag.clone();
2735                char_bag.extend(
2736                    String::from_utf8_lossy(&entry.path)
2737                        .chars()
2738                        .map(|c| c.to_ascii_lowercase()),
2739                );
2740                EntryKind::File(char_bag)
2741            };
2742            let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2743            Ok(Entry {
2744                id: ProjectEntryId::from_proto(entry.id),
2745                kind,
2746                path: path.clone(),
2747                inode: entry.inode,
2748                mtime: mtime.into(),
2749                is_symlink: entry.is_symlink,
2750                is_ignored: entry.is_ignored,
2751            })
2752        } else {
2753            Err(anyhow!(
2754                "missing mtime in remote worktree entry {:?}",
2755                entry.path
2756            ))
2757        }
2758    }
2759}
2760
2761#[cfg(test)]
2762mod tests {
2763    use super::*;
2764    use crate::fs::FakeFs;
2765    use anyhow::Result;
2766    use client::test::FakeHttpClient;
2767    use fs::RealFs;
2768    use gpui::TestAppContext;
2769    use rand::prelude::*;
2770    use serde_json::json;
2771    use std::{
2772        env,
2773        fmt::Write,
2774        time::{SystemTime, UNIX_EPOCH},
2775    };
2776    use util::test::temp_tree;
2777
2778    #[gpui::test]
2779    async fn test_traversal(cx: &mut TestAppContext) {
2780        let fs = FakeFs::new(cx.background());
2781        fs.insert_tree(
2782            "/root",
2783            json!({
2784               ".gitignore": "a/b\n",
2785               "a": {
2786                   "b": "",
2787                   "c": "",
2788               }
2789            }),
2790        )
2791        .await;
2792
2793        let http_client = FakeHttpClient::with_404_response();
2794        let client = Client::new(http_client);
2795
2796        let tree = Worktree::local(
2797            client,
2798            Arc::from(Path::new("/root")),
2799            true,
2800            fs,
2801            Default::default(),
2802            &mut cx.to_async(),
2803        )
2804        .await
2805        .unwrap();
2806        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2807            .await;
2808
2809        tree.read_with(cx, |tree, _| {
2810            assert_eq!(
2811                tree.entries(false)
2812                    .map(|entry| entry.path.as_ref())
2813                    .collect::<Vec<_>>(),
2814                vec![
2815                    Path::new(""),
2816                    Path::new(".gitignore"),
2817                    Path::new("a"),
2818                    Path::new("a/c"),
2819                ]
2820            );
2821            assert_eq!(
2822                tree.entries(true)
2823                    .map(|entry| entry.path.as_ref())
2824                    .collect::<Vec<_>>(),
2825                vec![
2826                    Path::new(""),
2827                    Path::new(".gitignore"),
2828                    Path::new("a"),
2829                    Path::new("a/b"),
2830                    Path::new("a/c"),
2831                ]
2832            );
2833        })
2834    }
2835
2836    #[gpui::test]
2837    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
2838        let dir = temp_tree(json!({
2839            ".git": {},
2840            ".gitignore": "ignored-dir\n",
2841            "tracked-dir": {
2842                "tracked-file1": "tracked contents",
2843            },
2844            "ignored-dir": {
2845                "ignored-file1": "ignored contents",
2846            }
2847        }));
2848
2849        let http_client = FakeHttpClient::with_404_response();
2850        let client = Client::new(http_client.clone());
2851
2852        let tree = Worktree::local(
2853            client,
2854            dir.path(),
2855            true,
2856            Arc::new(RealFs),
2857            Default::default(),
2858            &mut cx.to_async(),
2859        )
2860        .await
2861        .unwrap();
2862        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2863            .await;
2864        tree.flush_fs_events(&cx).await;
2865        cx.read(|cx| {
2866            let tree = tree.read(cx);
2867            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2868            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2869            assert_eq!(tracked.is_ignored, false);
2870            assert_eq!(ignored.is_ignored, true);
2871        });
2872
2873        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2874        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2875        tree.flush_fs_events(&cx).await;
2876        cx.read(|cx| {
2877            let tree = tree.read(cx);
2878            let dot_git = tree.entry_for_path(".git").unwrap();
2879            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2880            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2881            assert_eq!(tracked.is_ignored, false);
2882            assert_eq!(ignored.is_ignored, true);
2883            assert_eq!(dot_git.is_ignored, true);
2884        });
2885    }
2886
2887    #[gpui::test]
2888    async fn test_write_file(cx: &mut TestAppContext) {
2889        let dir = temp_tree(json!({
2890            ".git": {},
2891            ".gitignore": "ignored-dir\n",
2892            "tracked-dir": {},
2893            "ignored-dir": {}
2894        }));
2895
2896        let http_client = FakeHttpClient::with_404_response();
2897        let client = Client::new(http_client.clone());
2898
2899        let tree = Worktree::local(
2900            client,
2901            dir.path(),
2902            true,
2903            Arc::new(RealFs),
2904            Default::default(),
2905            &mut cx.to_async(),
2906        )
2907        .await
2908        .unwrap();
2909        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2910            .await;
2911        tree.flush_fs_events(&cx).await;
2912
2913        tree.update(cx, |tree, cx| {
2914            tree.as_local().unwrap().write_file(
2915                Path::new("tracked-dir/file.txt"),
2916                "hello".into(),
2917                cx,
2918            )
2919        })
2920        .await
2921        .unwrap();
2922        tree.update(cx, |tree, cx| {
2923            tree.as_local().unwrap().write_file(
2924                Path::new("ignored-dir/file.txt"),
2925                "world".into(),
2926                cx,
2927            )
2928        })
2929        .await
2930        .unwrap();
2931
2932        tree.read_with(cx, |tree, _| {
2933            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
2934            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
2935            assert_eq!(tracked.is_ignored, false);
2936            assert_eq!(ignored.is_ignored, true);
2937        });
2938    }
2939
2940    #[gpui::test(iterations = 100)]
2941    fn test_random(mut rng: StdRng) {
2942        let operations = env::var("OPERATIONS")
2943            .map(|o| o.parse().unwrap())
2944            .unwrap_or(40);
2945        let initial_entries = env::var("INITIAL_ENTRIES")
2946            .map(|o| o.parse().unwrap())
2947            .unwrap_or(20);
2948
2949        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2950        for _ in 0..initial_entries {
2951            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2952        }
2953        log::info!("Generated initial tree");
2954
2955        let (notify_tx, _notify_rx) = mpsc::unbounded();
2956        let fs = Arc::new(RealFs);
2957        let next_entry_id = Arc::new(AtomicUsize::new(0));
2958        let mut initial_snapshot = LocalSnapshot {
2959            abs_path: root_dir.path().into(),
2960            removed_entry_ids: Default::default(),
2961            ignores: Default::default(),
2962            next_entry_id: next_entry_id.clone(),
2963            snapshot: Snapshot {
2964                id: WorktreeId::from_usize(0),
2965                entries_by_path: Default::default(),
2966                entries_by_id: Default::default(),
2967                root_name: Default::default(),
2968                root_char_bag: Default::default(),
2969                scan_id: 0,
2970            },
2971            extension_counts: Default::default(),
2972        };
2973        initial_snapshot.insert_entry(
2974            Entry::new(
2975                Path::new("").into(),
2976                &smol::block_on(fs.metadata(root_dir.path()))
2977                    .unwrap()
2978                    .unwrap(),
2979                &next_entry_id,
2980                Default::default(),
2981            ),
2982            fs.as_ref(),
2983        );
2984        let mut scanner = BackgroundScanner::new(
2985            Arc::new(Mutex::new(initial_snapshot.clone())),
2986            notify_tx,
2987            fs.clone(),
2988            Arc::new(gpui::executor::Background::new()),
2989        );
2990        smol::block_on(scanner.scan_dirs()).unwrap();
2991        scanner.snapshot().check_invariants();
2992
2993        let mut events = Vec::new();
2994        let mut snapshots = Vec::new();
2995        let mut mutations_len = operations;
2996        while mutations_len > 1 {
2997            if !events.is_empty() && rng.gen_bool(0.4) {
2998                let len = rng.gen_range(0..=events.len());
2999                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
3000                log::info!("Delivering events: {:#?}", to_deliver);
3001                smol::block_on(scanner.process_events(to_deliver));
3002                scanner.snapshot().check_invariants();
3003            } else {
3004                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
3005                mutations_len -= 1;
3006            }
3007
3008            if rng.gen_bool(0.2) {
3009                snapshots.push(scanner.snapshot());
3010            }
3011        }
3012        log::info!("Quiescing: {:#?}", events);
3013        smol::block_on(scanner.process_events(events));
3014        scanner.snapshot().check_invariants();
3015
3016        let (notify_tx, _notify_rx) = mpsc::unbounded();
3017        let mut new_scanner = BackgroundScanner::new(
3018            Arc::new(Mutex::new(initial_snapshot)),
3019            notify_tx,
3020            scanner.fs.clone(),
3021            scanner.executor.clone(),
3022        );
3023        smol::block_on(new_scanner.scan_dirs()).unwrap();
3024        assert_eq!(
3025            scanner.snapshot().to_vec(true),
3026            new_scanner.snapshot().to_vec(true)
3027        );
3028
3029        for mut prev_snapshot in snapshots {
3030            let include_ignored = rng.gen::<bool>();
3031            if !include_ignored {
3032                let mut entries_by_path_edits = Vec::new();
3033                let mut entries_by_id_edits = Vec::new();
3034                for entry in prev_snapshot
3035                    .entries_by_id
3036                    .cursor::<()>()
3037                    .filter(|e| e.is_ignored)
3038                {
3039                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3040                    entries_by_id_edits.push(Edit::Remove(entry.id));
3041                }
3042
3043                prev_snapshot
3044                    .entries_by_path
3045                    .edit(entries_by_path_edits, &());
3046                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3047            }
3048
3049            let update = scanner
3050                .snapshot()
3051                .build_update(&prev_snapshot, 0, 0, include_ignored);
3052            prev_snapshot.apply_remote_update(update).unwrap();
3053            assert_eq!(
3054                prev_snapshot.to_vec(true),
3055                scanner.snapshot().to_vec(include_ignored)
3056            );
3057        }
3058    }
3059
3060    fn randomly_mutate_tree(
3061        root_path: &Path,
3062        insertion_probability: f64,
3063        rng: &mut impl Rng,
3064    ) -> Result<Vec<fsevent::Event>> {
3065        let root_path = root_path.canonicalize().unwrap();
3066        let (dirs, files) = read_dir_recursive(root_path.clone());
3067
3068        let mut events = Vec::new();
3069        let mut record_event = |path: PathBuf| {
3070            events.push(fsevent::Event {
3071                event_id: SystemTime::now()
3072                    .duration_since(UNIX_EPOCH)
3073                    .unwrap()
3074                    .as_secs(),
3075                flags: fsevent::StreamFlags::empty(),
3076                path,
3077            });
3078        };
3079
3080        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3081            let path = dirs.choose(rng).unwrap();
3082            let new_path = path.join(gen_name(rng));
3083
3084            if rng.gen() {
3085                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
3086                std::fs::create_dir(&new_path)?;
3087            } else {
3088                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
3089                std::fs::write(&new_path, "")?;
3090            }
3091            record_event(new_path);
3092        } else if rng.gen_bool(0.05) {
3093            let ignore_dir_path = dirs.choose(rng).unwrap();
3094            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3095
3096            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
3097            let files_to_ignore = {
3098                let len = rng.gen_range(0..=subfiles.len());
3099                subfiles.choose_multiple(rng, len)
3100            };
3101            let dirs_to_ignore = {
3102                let len = rng.gen_range(0..subdirs.len());
3103                subdirs.choose_multiple(rng, len)
3104            };
3105
3106            let mut ignore_contents = String::new();
3107            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3108                write!(
3109                    ignore_contents,
3110                    "{}\n",
3111                    path_to_ignore
3112                        .strip_prefix(&ignore_dir_path)?
3113                        .to_str()
3114                        .unwrap()
3115                )
3116                .unwrap();
3117            }
3118            log::info!(
3119                "Creating {:?} with contents:\n{}",
3120                ignore_path.strip_prefix(&root_path)?,
3121                ignore_contents
3122            );
3123            std::fs::write(&ignore_path, ignore_contents).unwrap();
3124            record_event(ignore_path);
3125        } else {
3126            let old_path = {
3127                let file_path = files.choose(rng);
3128                let dir_path = dirs[1..].choose(rng);
3129                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3130            };
3131
3132            let is_rename = rng.gen();
3133            if is_rename {
3134                let new_path_parent = dirs
3135                    .iter()
3136                    .filter(|d| !d.starts_with(old_path))
3137                    .choose(rng)
3138                    .unwrap();
3139
3140                let overwrite_existing_dir =
3141                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3142                let new_path = if overwrite_existing_dir {
3143                    std::fs::remove_dir_all(&new_path_parent).ok();
3144                    new_path_parent.to_path_buf()
3145                } else {
3146                    new_path_parent.join(gen_name(rng))
3147                };
3148
3149                log::info!(
3150                    "Renaming {:?} to {}{:?}",
3151                    old_path.strip_prefix(&root_path)?,
3152                    if overwrite_existing_dir {
3153                        "overwrite "
3154                    } else {
3155                        ""
3156                    },
3157                    new_path.strip_prefix(&root_path)?
3158                );
3159                std::fs::rename(&old_path, &new_path)?;
3160                record_event(old_path.clone());
3161                record_event(new_path);
3162            } else if old_path.is_dir() {
3163                let (dirs, files) = read_dir_recursive(old_path.clone());
3164
3165                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3166                std::fs::remove_dir_all(&old_path).unwrap();
3167                for file in files {
3168                    record_event(file);
3169                }
3170                for dir in dirs {
3171                    record_event(dir);
3172                }
3173            } else {
3174                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3175                std::fs::remove_file(old_path).unwrap();
3176                record_event(old_path.clone());
3177            }
3178        }
3179
3180        Ok(events)
3181    }
3182
3183    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3184        let child_entries = std::fs::read_dir(&path).unwrap();
3185        let mut dirs = vec![path];
3186        let mut files = Vec::new();
3187        for child_entry in child_entries {
3188            let child_path = child_entry.unwrap().path();
3189            if child_path.is_dir() {
3190                let (child_dirs, child_files) = read_dir_recursive(child_path);
3191                dirs.extend(child_dirs);
3192                files.extend(child_files);
3193            } else {
3194                files.push(child_path);
3195            }
3196        }
3197        (dirs, files)
3198    }
3199
3200    fn gen_name(rng: &mut impl Rng) -> String {
3201        (0..6)
3202            .map(|_| rng.sample(rand::distributions::Alphanumeric))
3203            .map(char::from)
3204            .collect()
3205    }
3206
3207    impl LocalSnapshot {
3208        fn check_invariants(&self) {
3209            let mut files = self.files(true, 0);
3210            let mut visible_files = self.files(false, 0);
3211            for entry in self.entries_by_path.cursor::<()>() {
3212                if entry.is_file() {
3213                    assert_eq!(files.next().unwrap().inode, entry.inode);
3214                    if !entry.is_ignored {
3215                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3216                    }
3217                }
3218            }
3219            assert!(files.next().is_none());
3220            assert!(visible_files.next().is_none());
3221
3222            let mut bfs_paths = Vec::new();
3223            let mut stack = vec![Path::new("")];
3224            while let Some(path) = stack.pop() {
3225                bfs_paths.push(path);
3226                let ix = stack.len();
3227                for child_entry in self.child_entries(path) {
3228                    stack.insert(ix, &child_entry.path);
3229                }
3230            }
3231
3232            let dfs_paths_via_iter = self
3233                .entries_by_path
3234                .cursor::<()>()
3235                .map(|e| e.path.as_ref())
3236                .collect::<Vec<_>>();
3237            assert_eq!(bfs_paths, dfs_paths_via_iter);
3238
3239            let dfs_paths_via_traversal = self
3240                .entries(true)
3241                .map(|e| e.path.as_ref())
3242                .collect::<Vec<_>>();
3243            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3244
3245            for (ignore_parent_path, _) in &self.ignores {
3246                assert!(self.entry_for_path(ignore_parent_path).is_some());
3247                assert!(self
3248                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3249                    .is_some());
3250            }
3251
3252            // Ensure extension counts are correct.
3253            let mut expected_extension_counts = HashMap::default();
3254            for extension in self.entries(false).filter_map(|e| e.path.extension()) {
3255                *expected_extension_counts
3256                    .entry(extension.into())
3257                    .or_insert(0) += 1;
3258            }
3259            assert_eq!(self.extension_counts, expected_extension_counts);
3260        }
3261
3262        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3263            let mut paths = Vec::new();
3264            for entry in self.entries_by_path.cursor::<()>() {
3265                if include_ignored || !entry.is_ignored {
3266                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3267                }
3268            }
3269            paths.sort_by(|a, b| a.0.cmp(&b.0));
3270            paths
3271        }
3272    }
3273}