worktree.rs

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