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>>> {
 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            copy.await?;
 798            let entry = this
 799                .update(&mut cx, |this, cx| {
 800                    this.as_local_mut().unwrap().refresh_entry(
 801                        new_path.clone(),
 802                        abs_new_path,
 803                        None,
 804                        cx,
 805                    )
 806                })
 807                .await?;
 808            this.update(&mut cx, |this, cx| {
 809                this.poll_snapshot(cx);
 810                this.as_local().unwrap().broadcast_snapshot()
 811            })
 812            .await;
 813            Ok(entry)
 814        }))
 815    }
 816
 817    fn write_entry_internal(
 818        &self,
 819        path: impl Into<Arc<Path>>,
 820        text_if_file: Option<Rope>,
 821        cx: &mut ModelContext<Worktree>,
 822    ) -> Task<Result<Entry>> {
 823        let path = path.into();
 824        let abs_path = self.absolutize(&path);
 825        let write = cx.background().spawn({
 826            let fs = self.fs.clone();
 827            let abs_path = abs_path.clone();
 828            async move {
 829                if let Some(text) = text_if_file {
 830                    fs.save(&abs_path, &text).await
 831                } else {
 832                    fs.create_dir(&abs_path).await
 833                }
 834            }
 835        });
 836
 837        cx.spawn(|this, mut cx| async move {
 838            write.await?;
 839            let entry = this
 840                .update(&mut cx, |this, cx| {
 841                    this.as_local_mut()
 842                        .unwrap()
 843                        .refresh_entry(path, abs_path, None, cx)
 844                })
 845                .await?;
 846            this.update(&mut cx, |this, cx| {
 847                this.poll_snapshot(cx);
 848                this.as_local().unwrap().broadcast_snapshot()
 849            })
 850            .await;
 851            Ok(entry)
 852        })
 853    }
 854
 855    fn refresh_entry(
 856        &self,
 857        path: Arc<Path>,
 858        abs_path: PathBuf,
 859        old_path: Option<Arc<Path>>,
 860        cx: &mut ModelContext<Worktree>,
 861    ) -> Task<Result<Entry>> {
 862        let fs = self.fs.clone();
 863        let root_char_bag;
 864        let next_entry_id;
 865        {
 866            let snapshot = self.background_snapshot.lock();
 867            root_char_bag = snapshot.root_char_bag;
 868            next_entry_id = snapshot.next_entry_id.clone();
 869        }
 870        cx.spawn_weak(|this, mut cx| async move {
 871            let mut entry = Entry::new(
 872                path.clone(),
 873                &fs.metadata(&abs_path)
 874                    .await?
 875                    .ok_or_else(|| anyhow!("could not read saved file metadata"))?,
 876                &next_entry_id,
 877                root_char_bag,
 878            );
 879
 880            let this = this
 881                .upgrade(&cx)
 882                .ok_or_else(|| anyhow!("worktree was dropped"))?;
 883            let (entry, snapshot, snapshots_tx) = this.read_with(&cx, |this, _| {
 884                let this = this.as_local().unwrap();
 885                let mut snapshot = this.background_snapshot.lock();
 886                entry.is_ignored = snapshot
 887                    .ignore_stack_for_path(&path, entry.is_dir())
 888                    .is_path_ignored(&path, entry.is_dir());
 889                if let Some(old_path) = old_path {
 890                    snapshot.remove_path(&old_path);
 891                }
 892                let entry = snapshot.insert_entry(entry, fs.as_ref());
 893                snapshot.scan_id += 1;
 894                let snapshots_tx = this.share.as_ref().map(|s| s.snapshots_tx.clone());
 895                (entry, snapshot.clone(), snapshots_tx)
 896            });
 897            this.update(&mut cx, |this, cx| this.poll_snapshot(cx));
 898
 899            if let Some(snapshots_tx) = snapshots_tx {
 900                snapshots_tx.send(snapshot).await.ok();
 901            }
 902
 903            Ok(entry)
 904        })
 905    }
 906
 907    pub fn register(
 908        &mut self,
 909        project_id: u64,
 910        cx: &mut ModelContext<Worktree>,
 911    ) -> Task<anyhow::Result<()>> {
 912        if self.registration != Registration::None {
 913            return Task::ready(Ok(()));
 914        }
 915
 916        self.registration = Registration::Pending;
 917        let client = self.client.clone();
 918        let register_message = proto::RegisterWorktree {
 919            project_id,
 920            worktree_id: self.id().to_proto(),
 921            root_name: self.root_name().to_string(),
 922            visible: self.visible,
 923        };
 924        let request = client.request(register_message);
 925        cx.spawn(|this, mut cx| async move {
 926            let response = request.await;
 927            this.update(&mut cx, |this, _| {
 928                let worktree = this.as_local_mut().unwrap();
 929                match response {
 930                    Ok(_) => {
 931                        if worktree.registration == Registration::Pending {
 932                            worktree.registration = Registration::Done { project_id };
 933                        }
 934                        Ok(())
 935                    }
 936                    Err(error) => {
 937                        worktree.registration = Registration::None;
 938                        Err(error)
 939                    }
 940                }
 941            })
 942        })
 943    }
 944
 945    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
 946        let register = self.register(project_id, cx);
 947        let (share_tx, share_rx) = oneshot::channel();
 948        let (snapshots_to_send_tx, snapshots_to_send_rx) =
 949            smol::channel::unbounded::<LocalSnapshot>();
 950        if self.share.is_some() {
 951            let _ = share_tx.send(Ok(()));
 952        } else {
 953            let rpc = self.client.clone();
 954            let worktree_id = cx.model_id() as u64;
 955            let maintain_remote_snapshot = cx.background().spawn({
 956                let rpc = rpc.clone();
 957                let diagnostic_summaries = self.diagnostic_summaries.clone();
 958                async move {
 959                    let mut prev_snapshot = match snapshots_to_send_rx.recv().await {
 960                        Ok(snapshot) => {
 961                            if let Err(error) = rpc
 962                                .request(proto::UpdateWorktree {
 963                                    project_id,
 964                                    worktree_id,
 965                                    root_name: snapshot.root_name().to_string(),
 966                                    updated_entries: snapshot
 967                                        .entries_by_path
 968                                        .iter()
 969                                        .filter(|e| !e.is_ignored)
 970                                        .map(Into::into)
 971                                        .collect(),
 972                                    removed_entries: Default::default(),
 973                                    scan_id: snapshot.scan_id as u64,
 974                                })
 975                                .await
 976                            {
 977                                let _ = share_tx.send(Err(error));
 978                                return Err(anyhow!("failed to send initial update worktree"));
 979                            } else {
 980                                let _ = share_tx.send(Ok(()));
 981                                snapshot
 982                            }
 983                        }
 984                        Err(error) => {
 985                            let _ = share_tx.send(Err(error.into()));
 986                            return Err(anyhow!("failed to send initial update worktree"));
 987                        }
 988                    };
 989
 990                    for (path, summary) in diagnostic_summaries.iter() {
 991                        rpc.send(proto::UpdateDiagnosticSummary {
 992                            project_id,
 993                            worktree_id,
 994                            summary: Some(summary.to_proto(&path.0)),
 995                        })?;
 996                    }
 997
 998                    // Stream ignored entries in chunks.
 999                    {
1000                        let mut ignored_entries = prev_snapshot
1001                            .entries_by_path
1002                            .iter()
1003                            .filter(|e| e.is_ignored);
1004                        let mut ignored_entries_to_send = Vec::new();
1005                        loop {
1006                            #[cfg(any(test, feature = "test-support"))]
1007                            const CHUNK_SIZE: usize = 2;
1008                            #[cfg(not(any(test, feature = "test-support")))]
1009                            const CHUNK_SIZE: usize = 256;
1010
1011                            let entry = ignored_entries.next();
1012                            if ignored_entries_to_send.len() >= CHUNK_SIZE || entry.is_none() {
1013                                rpc.request(proto::UpdateWorktree {
1014                                    project_id,
1015                                    worktree_id,
1016                                    root_name: prev_snapshot.root_name().to_string(),
1017                                    updated_entries: mem::take(&mut ignored_entries_to_send),
1018                                    removed_entries: Default::default(),
1019                                    scan_id: prev_snapshot.scan_id as u64,
1020                                })
1021                                .await?;
1022                            }
1023
1024                            if let Some(entry) = entry {
1025                                ignored_entries_to_send.push(entry.into());
1026                            } else {
1027                                break;
1028                            }
1029                        }
1030                    }
1031
1032                    while let Ok(snapshot) = snapshots_to_send_rx.recv().await {
1033                        let message =
1034                            snapshot.build_update(&prev_snapshot, project_id, worktree_id, true);
1035                        rpc.request(message).await?;
1036                        prev_snapshot = snapshot;
1037                    }
1038
1039                    Ok::<_, anyhow::Error>(())
1040                }
1041                .log_err()
1042            });
1043            self.share = Some(ShareState {
1044                project_id,
1045                snapshots_tx: snapshots_to_send_tx.clone(),
1046                _maintain_remote_snapshot: Some(maintain_remote_snapshot),
1047            });
1048        }
1049
1050        cx.spawn_weak(|this, cx| async move {
1051            register.await?;
1052            if let Some(this) = this.upgrade(&cx) {
1053                this.read_with(&cx, |this, _| {
1054                    let this = this.as_local().unwrap();
1055                    let _ = snapshots_to_send_tx.try_send(this.snapshot());
1056                });
1057            }
1058            share_rx
1059                .await
1060                .unwrap_or_else(|_| Err(anyhow!("share ended")))
1061        })
1062    }
1063
1064    pub fn unregister(&mut self) {
1065        self.unshare();
1066        self.registration = Registration::None;
1067    }
1068
1069    pub fn unshare(&mut self) {
1070        self.share.take();
1071    }
1072
1073    pub fn is_shared(&self) -> bool {
1074        self.share.is_some()
1075    }
1076
1077    fn broadcast_snapshot(&self) -> impl Future<Output = ()> {
1078        let mut to_send = None;
1079        if !self.is_scanning() {
1080            if let Some(share) = self.share.as_ref() {
1081                to_send = Some((self.snapshot(), share.snapshots_tx.clone()));
1082            }
1083        }
1084
1085        async move {
1086            if let Some((snapshot, snapshots_to_send_tx)) = to_send {
1087                if let Err(err) = snapshots_to_send_tx.send(snapshot).await {
1088                    log::error!("error submitting snapshot to send {}", err);
1089                }
1090            }
1091        }
1092    }
1093}
1094
1095impl RemoteWorktree {
1096    fn snapshot(&self) -> Snapshot {
1097        self.snapshot.clone()
1098    }
1099
1100    pub fn update_from_remote(
1101        &mut self,
1102        envelope: TypedEnvelope<proto::UpdateWorktree>,
1103    ) -> Result<()> {
1104        self.updates_tx
1105            .unbounded_send(envelope.payload)
1106            .expect("consumer runs to completion");
1107        Ok(())
1108    }
1109
1110    fn wait_for_snapshot(&self, scan_id: usize) -> impl Future<Output = ()> {
1111        let mut rx = self.last_scan_id_rx.clone();
1112        async move {
1113            while let Some(applied_scan_id) = rx.next().await {
1114                if applied_scan_id >= scan_id {
1115                    return;
1116                }
1117            }
1118        }
1119    }
1120
1121    pub fn update_diagnostic_summary(
1122        &mut self,
1123        path: Arc<Path>,
1124        summary: &proto::DiagnosticSummary,
1125    ) {
1126        let summary = DiagnosticSummary {
1127            error_count: summary.error_count as usize,
1128            warning_count: summary.warning_count as usize,
1129        };
1130        if summary.is_empty() {
1131            self.diagnostic_summaries.remove(&PathKey(path.clone()));
1132        } else {
1133            self.diagnostic_summaries
1134                .insert(PathKey(path.clone()), summary);
1135        }
1136    }
1137
1138    pub fn insert_entry(
1139        &self,
1140        entry: proto::Entry,
1141        scan_id: usize,
1142        cx: &mut ModelContext<Worktree>,
1143    ) -> Task<Result<Entry>> {
1144        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1145        cx.spawn(|this, mut cx| async move {
1146            wait_for_snapshot.await;
1147            this.update(&mut cx, |worktree, _| {
1148                let worktree = worktree.as_remote_mut().unwrap();
1149                let mut snapshot = worktree.background_snapshot.lock();
1150                let entry = snapshot.insert_entry(entry);
1151                worktree.snapshot = snapshot.clone();
1152                entry
1153            })
1154        })
1155    }
1156
1157    pub(crate) fn delete_entry(
1158        &self,
1159        id: ProjectEntryId,
1160        scan_id: usize,
1161        cx: &mut ModelContext<Worktree>,
1162    ) -> Task<Result<()>> {
1163        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1164        cx.spawn(|this, mut cx| async move {
1165            wait_for_snapshot.await;
1166            this.update(&mut cx, |worktree, _| {
1167                let worktree = worktree.as_remote_mut().unwrap();
1168                let mut snapshot = worktree.background_snapshot.lock();
1169                snapshot.delete_entry(id);
1170                worktree.snapshot = snapshot.clone();
1171            });
1172            Ok(())
1173        })
1174    }
1175}
1176
1177impl Snapshot {
1178    pub fn id(&self) -> WorktreeId {
1179        self.id
1180    }
1181
1182    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1183        self.entries_by_id.get(&entry_id, &()).is_some()
1184    }
1185
1186    pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1187        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1188        let old_entry = self.entries_by_id.insert_or_replace(
1189            PathEntry {
1190                id: entry.id,
1191                path: entry.path.clone(),
1192                is_ignored: entry.is_ignored,
1193                scan_id: 0,
1194            },
1195            &(),
1196        );
1197        if let Some(old_entry) = old_entry {
1198            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1199        }
1200        self.entries_by_path.insert_or_replace(entry.clone(), &());
1201        Ok(entry)
1202    }
1203
1204    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> bool {
1205        if let Some(removed_entry) = self.entries_by_id.remove(&entry_id, &()) {
1206            self.entries_by_path = {
1207                let mut cursor = self.entries_by_path.cursor();
1208                let mut new_entries_by_path =
1209                    cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1210                while let Some(entry) = cursor.item() {
1211                    if entry.path.starts_with(&removed_entry.path) {
1212                        self.entries_by_id.remove(&entry.id, &());
1213                        cursor.next(&());
1214                    } else {
1215                        break;
1216                    }
1217                }
1218                new_entries_by_path.push_tree(cursor.suffix(&()), &());
1219                new_entries_by_path
1220            };
1221
1222            true
1223        } else {
1224            false
1225        }
1226    }
1227
1228    pub(crate) fn apply_remote_update(&mut self, update: proto::UpdateWorktree) -> Result<()> {
1229        let mut entries_by_path_edits = Vec::new();
1230        let mut entries_by_id_edits = Vec::new();
1231        for entry_id in update.removed_entries {
1232            let entry = self
1233                .entry_for_id(ProjectEntryId::from_proto(entry_id))
1234                .ok_or_else(|| anyhow!("unknown entry"))?;
1235            entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1236            entries_by_id_edits.push(Edit::Remove(entry.id));
1237        }
1238
1239        for entry in update.updated_entries {
1240            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1241            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1242                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1243            }
1244            entries_by_id_edits.push(Edit::Insert(PathEntry {
1245                id: entry.id,
1246                path: entry.path.clone(),
1247                is_ignored: entry.is_ignored,
1248                scan_id: 0,
1249            }));
1250            entries_by_path_edits.push(Edit::Insert(entry));
1251        }
1252
1253        self.entries_by_path.edit(entries_by_path_edits, &());
1254        self.entries_by_id.edit(entries_by_id_edits, &());
1255        self.scan_id = update.scan_id as usize;
1256
1257        Ok(())
1258    }
1259
1260    pub fn file_count(&self) -> usize {
1261        self.entries_by_path.summary().file_count
1262    }
1263
1264    pub fn visible_file_count(&self) -> usize {
1265        self.entries_by_path.summary().visible_file_count
1266    }
1267
1268    fn traverse_from_offset(
1269        &self,
1270        include_dirs: bool,
1271        include_ignored: bool,
1272        start_offset: usize,
1273    ) -> Traversal {
1274        let mut cursor = self.entries_by_path.cursor();
1275        cursor.seek(
1276            &TraversalTarget::Count {
1277                count: start_offset,
1278                include_dirs,
1279                include_ignored,
1280            },
1281            Bias::Right,
1282            &(),
1283        );
1284        Traversal {
1285            cursor,
1286            include_dirs,
1287            include_ignored,
1288        }
1289    }
1290
1291    fn traverse_from_path(
1292        &self,
1293        include_dirs: bool,
1294        include_ignored: bool,
1295        path: &Path,
1296    ) -> Traversal {
1297        let mut cursor = self.entries_by_path.cursor();
1298        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1299        Traversal {
1300            cursor,
1301            include_dirs,
1302            include_ignored,
1303        }
1304    }
1305
1306    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1307        self.traverse_from_offset(false, include_ignored, start)
1308    }
1309
1310    pub fn entries(&self, include_ignored: bool) -> Traversal {
1311        self.traverse_from_offset(true, include_ignored, 0)
1312    }
1313
1314    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1315        let empty_path = Path::new("");
1316        self.entries_by_path
1317            .cursor::<()>()
1318            .filter(move |entry| entry.path.as_ref() != empty_path)
1319            .map(|entry| &entry.path)
1320    }
1321
1322    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1323        let mut cursor = self.entries_by_path.cursor();
1324        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1325        let traversal = Traversal {
1326            cursor,
1327            include_dirs: true,
1328            include_ignored: true,
1329        };
1330        ChildEntriesIter {
1331            traversal,
1332            parent_path,
1333        }
1334    }
1335
1336    pub fn root_entry(&self) -> Option<&Entry> {
1337        self.entry_for_path("")
1338    }
1339
1340    pub fn root_name(&self) -> &str {
1341        &self.root_name
1342    }
1343
1344    pub fn scan_id(&self) -> usize {
1345        self.scan_id
1346    }
1347
1348    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1349        let path = path.as_ref();
1350        self.traverse_from_path(true, true, path)
1351            .entry()
1352            .and_then(|entry| {
1353                if entry.path.as_ref() == path {
1354                    Some(entry)
1355                } else {
1356                    None
1357                }
1358            })
1359    }
1360
1361    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1362        let entry = self.entries_by_id.get(&id, &())?;
1363        self.entry_for_path(&entry.path)
1364    }
1365
1366    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1367        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1368    }
1369}
1370
1371impl LocalSnapshot {
1372    pub fn abs_path(&self) -> &Arc<Path> {
1373        &self.abs_path
1374    }
1375
1376    #[cfg(test)]
1377    pub(crate) fn to_proto(
1378        &self,
1379        diagnostic_summaries: &TreeMap<PathKey, DiagnosticSummary>,
1380        visible: bool,
1381    ) -> proto::Worktree {
1382        let root_name = self.root_name.clone();
1383        proto::Worktree {
1384            id: self.id.0 as u64,
1385            root_name,
1386            entries: self
1387                .entries_by_path
1388                .iter()
1389                .filter(|e| !e.is_ignored)
1390                .map(Into::into)
1391                .collect(),
1392            diagnostic_summaries: diagnostic_summaries
1393                .iter()
1394                .map(|(path, summary)| summary.to_proto(&path.0))
1395                .collect(),
1396            visible,
1397            scan_id: self.scan_id as u64,
1398        }
1399    }
1400
1401    pub(crate) fn build_update(
1402        &self,
1403        other: &Self,
1404        project_id: u64,
1405        worktree_id: u64,
1406        include_ignored: bool,
1407    ) -> proto::UpdateWorktree {
1408        let mut updated_entries = Vec::new();
1409        let mut removed_entries = Vec::new();
1410        let mut self_entries = self
1411            .entries_by_id
1412            .cursor::<()>()
1413            .filter(|e| include_ignored || !e.is_ignored)
1414            .peekable();
1415        let mut other_entries = other
1416            .entries_by_id
1417            .cursor::<()>()
1418            .filter(|e| include_ignored || !e.is_ignored)
1419            .peekable();
1420        loop {
1421            match (self_entries.peek(), other_entries.peek()) {
1422                (Some(self_entry), Some(other_entry)) => {
1423                    match Ord::cmp(&self_entry.id, &other_entry.id) {
1424                        Ordering::Less => {
1425                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1426                            updated_entries.push(entry);
1427                            self_entries.next();
1428                        }
1429                        Ordering::Equal => {
1430                            if self_entry.scan_id != other_entry.scan_id {
1431                                let entry = self.entry_for_id(self_entry.id).unwrap().into();
1432                                updated_entries.push(entry);
1433                            }
1434
1435                            self_entries.next();
1436                            other_entries.next();
1437                        }
1438                        Ordering::Greater => {
1439                            removed_entries.push(other_entry.id.to_proto());
1440                            other_entries.next();
1441                        }
1442                    }
1443                }
1444                (Some(self_entry), None) => {
1445                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1446                    updated_entries.push(entry);
1447                    self_entries.next();
1448                }
1449                (None, Some(other_entry)) => {
1450                    removed_entries.push(other_entry.id.to_proto());
1451                    other_entries.next();
1452                }
1453                (None, None) => break,
1454            }
1455        }
1456
1457        proto::UpdateWorktree {
1458            project_id,
1459            worktree_id,
1460            root_name: self.root_name().to_string(),
1461            updated_entries,
1462            removed_entries,
1463            scan_id: self.scan_id as u64,
1464        }
1465    }
1466
1467    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1468        if !entry.is_dir() && entry.path.file_name() == Some(&GITIGNORE) {
1469            let abs_path = self.abs_path.join(&entry.path);
1470            match build_gitignore(&abs_path, fs) {
1471                Ok(ignore) => {
1472                    let ignore_dir_path = entry.path.parent().unwrap();
1473                    self.ignores
1474                        .insert(ignore_dir_path.into(), (Arc::new(ignore), self.scan_id));
1475                }
1476                Err(error) => {
1477                    log::error!(
1478                        "error loading .gitignore file {:?} - {:?}",
1479                        &entry.path,
1480                        error
1481                    );
1482                }
1483            }
1484        }
1485
1486        self.reuse_entry_id(&mut entry);
1487        self.entries_by_path.insert_or_replace(entry.clone(), &());
1488        let scan_id = self.scan_id;
1489        self.entries_by_id.insert_or_replace(
1490            PathEntry {
1491                id: entry.id,
1492                path: entry.path.clone(),
1493                is_ignored: entry.is_ignored,
1494                scan_id,
1495            },
1496            &(),
1497        );
1498        entry
1499    }
1500
1501    fn populate_dir(
1502        &mut self,
1503        parent_path: Arc<Path>,
1504        entries: impl IntoIterator<Item = Entry>,
1505        ignore: Option<Arc<Gitignore>>,
1506    ) {
1507        let mut parent_entry = if let Some(parent_entry) =
1508            self.entries_by_path.get(&PathKey(parent_path.clone()), &())
1509        {
1510            parent_entry.clone()
1511        } else {
1512            log::warn!(
1513                "populating a directory {:?} that has been removed",
1514                parent_path
1515            );
1516            return;
1517        };
1518
1519        if let Some(ignore) = ignore {
1520            self.ignores.insert(parent_path, (ignore, self.scan_id));
1521        }
1522        if matches!(parent_entry.kind, EntryKind::PendingDir) {
1523            parent_entry.kind = EntryKind::Dir;
1524        } else {
1525            unreachable!();
1526        }
1527
1528        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1529        let mut entries_by_id_edits = Vec::new();
1530
1531        for mut entry in entries {
1532            self.reuse_entry_id(&mut entry);
1533            entries_by_id_edits.push(Edit::Insert(PathEntry {
1534                id: entry.id,
1535                path: entry.path.clone(),
1536                is_ignored: entry.is_ignored,
1537                scan_id: self.scan_id,
1538            }));
1539            entries_by_path_edits.push(Edit::Insert(entry));
1540        }
1541
1542        self.entries_by_path.edit(entries_by_path_edits, &());
1543        self.entries_by_id.edit(entries_by_id_edits, &());
1544    }
1545
1546    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1547        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1548            entry.id = removed_entry_id;
1549        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1550            entry.id = existing_entry.id;
1551        }
1552    }
1553
1554    fn remove_path(&mut self, path: &Path) {
1555        let mut new_entries;
1556        let removed_entries;
1557        {
1558            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1559            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1560            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1561            new_entries.push_tree(cursor.suffix(&()), &());
1562        }
1563        self.entries_by_path = new_entries;
1564
1565        let mut entries_by_id_edits = Vec::new();
1566        for entry in removed_entries.cursor::<()>() {
1567            let removed_entry_id = self
1568                .removed_entry_ids
1569                .entry(entry.inode)
1570                .or_insert(entry.id);
1571            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1572            entries_by_id_edits.push(Edit::Remove(entry.id));
1573        }
1574        self.entries_by_id.edit(entries_by_id_edits, &());
1575
1576        if path.file_name() == Some(&GITIGNORE) {
1577            if let Some((_, scan_id)) = self.ignores.get_mut(path.parent().unwrap()) {
1578                *scan_id = self.snapshot.scan_id;
1579            }
1580        }
1581    }
1582
1583    fn ignore_stack_for_path(&self, path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1584        let mut new_ignores = Vec::new();
1585        for ancestor in path.ancestors().skip(1) {
1586            if let Some((ignore, _)) = self.ignores.get(ancestor) {
1587                new_ignores.push((ancestor, Some(ignore.clone())));
1588            } else {
1589                new_ignores.push((ancestor, None));
1590            }
1591        }
1592
1593        let mut ignore_stack = IgnoreStack::none();
1594        for (parent_path, ignore) in new_ignores.into_iter().rev() {
1595            if ignore_stack.is_path_ignored(&parent_path, true) {
1596                ignore_stack = IgnoreStack::all();
1597                break;
1598            } else if let Some(ignore) = ignore {
1599                ignore_stack = ignore_stack.append(Arc::from(parent_path), ignore);
1600            }
1601        }
1602
1603        if ignore_stack.is_path_ignored(path, is_dir) {
1604            ignore_stack = IgnoreStack::all();
1605        }
1606
1607        ignore_stack
1608    }
1609}
1610
1611fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1612    let contents = smol::block_on(fs.load(&abs_path))?;
1613    let parent = abs_path.parent().unwrap_or(Path::new("/"));
1614    let mut builder = GitignoreBuilder::new(parent);
1615    for line in contents.lines() {
1616        builder.add_line(Some(abs_path.into()), line)?;
1617    }
1618    Ok(builder.build()?)
1619}
1620
1621impl WorktreeId {
1622    pub fn from_usize(handle_id: usize) -> Self {
1623        Self(handle_id)
1624    }
1625
1626    pub(crate) fn from_proto(id: u64) -> Self {
1627        Self(id as usize)
1628    }
1629
1630    pub fn to_proto(&self) -> u64 {
1631        self.0 as u64
1632    }
1633
1634    pub fn to_usize(&self) -> usize {
1635        self.0
1636    }
1637}
1638
1639impl fmt::Display for WorktreeId {
1640    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1641        self.0.fmt(f)
1642    }
1643}
1644
1645impl Deref for Worktree {
1646    type Target = Snapshot;
1647
1648    fn deref(&self) -> &Self::Target {
1649        match self {
1650            Worktree::Local(worktree) => &worktree.snapshot,
1651            Worktree::Remote(worktree) => &worktree.snapshot,
1652        }
1653    }
1654}
1655
1656impl Deref for LocalWorktree {
1657    type Target = LocalSnapshot;
1658
1659    fn deref(&self) -> &Self::Target {
1660        &self.snapshot
1661    }
1662}
1663
1664impl Deref for RemoteWorktree {
1665    type Target = Snapshot;
1666
1667    fn deref(&self) -> &Self::Target {
1668        &self.snapshot
1669    }
1670}
1671
1672impl fmt::Debug for LocalWorktree {
1673    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1674        self.snapshot.fmt(f)
1675    }
1676}
1677
1678impl fmt::Debug for Snapshot {
1679    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1680        struct EntriesById<'a>(&'a SumTree<PathEntry>);
1681        struct EntriesByPath<'a>(&'a SumTree<Entry>);
1682
1683        impl<'a> fmt::Debug for EntriesByPath<'a> {
1684            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1685                f.debug_map()
1686                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
1687                    .finish()
1688            }
1689        }
1690
1691        impl<'a> fmt::Debug for EntriesById<'a> {
1692            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1693                f.debug_list().entries(self.0.iter()).finish()
1694            }
1695        }
1696
1697        f.debug_struct("Snapshot")
1698            .field("id", &self.id)
1699            .field("root_name", &self.root_name)
1700            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
1701            .field("entries_by_id", &EntriesById(&self.entries_by_id))
1702            .finish()
1703    }
1704}
1705
1706#[derive(Clone, PartialEq)]
1707pub struct File {
1708    pub worktree: ModelHandle<Worktree>,
1709    pub path: Arc<Path>,
1710    pub mtime: SystemTime,
1711    pub(crate) entry_id: Option<ProjectEntryId>,
1712    pub(crate) is_local: bool,
1713}
1714
1715impl language::File for File {
1716    fn as_local(&self) -> Option<&dyn language::LocalFile> {
1717        if self.is_local {
1718            Some(self)
1719        } else {
1720            None
1721        }
1722    }
1723
1724    fn mtime(&self) -> SystemTime {
1725        self.mtime
1726    }
1727
1728    fn path(&self) -> &Arc<Path> {
1729        &self.path
1730    }
1731
1732    fn full_path(&self, cx: &AppContext) -> PathBuf {
1733        let mut full_path = PathBuf::new();
1734        full_path.push(self.worktree.read(cx).root_name());
1735        if self.path.components().next().is_some() {
1736            full_path.push(&self.path);
1737        }
1738        full_path
1739    }
1740
1741    /// Returns the last component of this handle's absolute path. If this handle refers to the root
1742    /// of its worktree, then this method will return the name of the worktree itself.
1743    fn file_name(&self, cx: &AppContext) -> OsString {
1744        self.path
1745            .file_name()
1746            .map(|name| name.into())
1747            .unwrap_or_else(|| OsString::from(&self.worktree.read(cx).root_name))
1748    }
1749
1750    fn is_deleted(&self) -> bool {
1751        self.entry_id.is_none()
1752    }
1753
1754    fn save(
1755        &self,
1756        buffer_id: u64,
1757        text: Rope,
1758        version: clock::Global,
1759        cx: &mut MutableAppContext,
1760    ) -> Task<Result<(clock::Global, SystemTime)>> {
1761        self.worktree.update(cx, |worktree, cx| match worktree {
1762            Worktree::Local(worktree) => {
1763                let rpc = worktree.client.clone();
1764                let project_id = worktree.share.as_ref().map(|share| share.project_id);
1765                let save = worktree.write_file(self.path.clone(), text, cx);
1766                cx.background().spawn(async move {
1767                    let entry = save.await?;
1768                    if let Some(project_id) = project_id {
1769                        rpc.send(proto::BufferSaved {
1770                            project_id,
1771                            buffer_id,
1772                            version: serialize_version(&version),
1773                            mtime: Some(entry.mtime.into()),
1774                        })?;
1775                    }
1776                    Ok((version, entry.mtime))
1777                })
1778            }
1779            Worktree::Remote(worktree) => {
1780                let rpc = worktree.client.clone();
1781                let project_id = worktree.project_id;
1782                cx.foreground().spawn(async move {
1783                    let response = rpc
1784                        .request(proto::SaveBuffer {
1785                            project_id,
1786                            buffer_id,
1787                            version: serialize_version(&version),
1788                        })
1789                        .await?;
1790                    let version = deserialize_version(response.version);
1791                    let mtime = response
1792                        .mtime
1793                        .ok_or_else(|| anyhow!("missing mtime"))?
1794                        .into();
1795                    Ok((version, mtime))
1796                })
1797            }
1798        })
1799    }
1800
1801    fn as_any(&self) -> &dyn Any {
1802        self
1803    }
1804
1805    fn to_proto(&self) -> rpc::proto::File {
1806        rpc::proto::File {
1807            worktree_id: self.worktree.id() as u64,
1808            entry_id: self.entry_id.map(|entry_id| entry_id.to_proto()),
1809            path: self.path.to_string_lossy().into(),
1810            mtime: Some(self.mtime.into()),
1811        }
1812    }
1813}
1814
1815impl language::LocalFile for File {
1816    fn abs_path(&self, cx: &AppContext) -> PathBuf {
1817        self.worktree
1818            .read(cx)
1819            .as_local()
1820            .unwrap()
1821            .abs_path
1822            .join(&self.path)
1823    }
1824
1825    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
1826        let worktree = self.worktree.read(cx).as_local().unwrap();
1827        let abs_path = worktree.absolutize(&self.path);
1828        let fs = worktree.fs.clone();
1829        cx.background()
1830            .spawn(async move { fs.load(&abs_path).await })
1831    }
1832
1833    fn buffer_reloaded(
1834        &self,
1835        buffer_id: u64,
1836        version: &clock::Global,
1837        mtime: SystemTime,
1838        cx: &mut MutableAppContext,
1839    ) {
1840        let worktree = self.worktree.read(cx).as_local().unwrap();
1841        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
1842            worktree
1843                .client
1844                .send(proto::BufferReloaded {
1845                    project_id,
1846                    buffer_id,
1847                    version: serialize_version(&version),
1848                    mtime: Some(mtime.into()),
1849                })
1850                .log_err();
1851        }
1852    }
1853}
1854
1855impl File {
1856    pub fn from_proto(
1857        proto: rpc::proto::File,
1858        worktree: ModelHandle<Worktree>,
1859        cx: &AppContext,
1860    ) -> Result<Self> {
1861        let worktree_id = worktree
1862            .read(cx)
1863            .as_remote()
1864            .ok_or_else(|| anyhow!("not remote"))?
1865            .id();
1866
1867        if worktree_id.to_proto() != proto.worktree_id {
1868            return Err(anyhow!("worktree id does not match file"));
1869        }
1870
1871        Ok(Self {
1872            worktree,
1873            path: Path::new(&proto.path).into(),
1874            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
1875            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
1876            is_local: false,
1877        })
1878    }
1879
1880    pub fn from_dyn(file: Option<&dyn language::File>) -> Option<&Self> {
1881        file.and_then(|f| f.as_any().downcast_ref())
1882    }
1883
1884    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
1885        self.worktree.read(cx).id()
1886    }
1887
1888    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1889        self.entry_id
1890    }
1891}
1892
1893#[derive(Clone, Debug, PartialEq, Eq)]
1894pub struct Entry {
1895    pub id: ProjectEntryId,
1896    pub kind: EntryKind,
1897    pub path: Arc<Path>,
1898    pub inode: u64,
1899    pub mtime: SystemTime,
1900    pub is_symlink: bool,
1901    pub is_ignored: bool,
1902}
1903
1904#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1905pub enum EntryKind {
1906    PendingDir,
1907    Dir,
1908    File(CharBag),
1909}
1910
1911impl Entry {
1912    fn new(
1913        path: Arc<Path>,
1914        metadata: &fs::Metadata,
1915        next_entry_id: &AtomicUsize,
1916        root_char_bag: CharBag,
1917    ) -> Self {
1918        Self {
1919            id: ProjectEntryId::new(next_entry_id),
1920            kind: if metadata.is_dir {
1921                EntryKind::PendingDir
1922            } else {
1923                EntryKind::File(char_bag_for_path(root_char_bag, &path))
1924            },
1925            path,
1926            inode: metadata.inode,
1927            mtime: metadata.mtime,
1928            is_symlink: metadata.is_symlink,
1929            is_ignored: false,
1930        }
1931    }
1932
1933    pub fn is_dir(&self) -> bool {
1934        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
1935    }
1936
1937    pub fn is_file(&self) -> bool {
1938        matches!(self.kind, EntryKind::File(_))
1939    }
1940}
1941
1942impl sum_tree::Item for Entry {
1943    type Summary = EntrySummary;
1944
1945    fn summary(&self) -> Self::Summary {
1946        let visible_count = if self.is_ignored { 0 } else { 1 };
1947        let file_count;
1948        let visible_file_count;
1949        if self.is_file() {
1950            file_count = 1;
1951            visible_file_count = visible_count;
1952        } else {
1953            file_count = 0;
1954            visible_file_count = 0;
1955        }
1956
1957        EntrySummary {
1958            max_path: self.path.clone(),
1959            count: 1,
1960            visible_count,
1961            file_count,
1962            visible_file_count,
1963        }
1964    }
1965}
1966
1967impl sum_tree::KeyedItem for Entry {
1968    type Key = PathKey;
1969
1970    fn key(&self) -> Self::Key {
1971        PathKey(self.path.clone())
1972    }
1973}
1974
1975#[derive(Clone, Debug)]
1976pub struct EntrySummary {
1977    max_path: Arc<Path>,
1978    count: usize,
1979    visible_count: usize,
1980    file_count: usize,
1981    visible_file_count: usize,
1982}
1983
1984impl Default for EntrySummary {
1985    fn default() -> Self {
1986        Self {
1987            max_path: Arc::from(Path::new("")),
1988            count: 0,
1989            visible_count: 0,
1990            file_count: 0,
1991            visible_file_count: 0,
1992        }
1993    }
1994}
1995
1996impl sum_tree::Summary for EntrySummary {
1997    type Context = ();
1998
1999    fn add_summary(&mut self, rhs: &Self, _: &()) {
2000        self.max_path = rhs.max_path.clone();
2001        self.count += rhs.count;
2002        self.visible_count += rhs.visible_count;
2003        self.file_count += rhs.file_count;
2004        self.visible_file_count += rhs.visible_file_count;
2005    }
2006}
2007
2008#[derive(Clone, Debug)]
2009struct PathEntry {
2010    id: ProjectEntryId,
2011    path: Arc<Path>,
2012    is_ignored: bool,
2013    scan_id: usize,
2014}
2015
2016impl sum_tree::Item for PathEntry {
2017    type Summary = PathEntrySummary;
2018
2019    fn summary(&self) -> Self::Summary {
2020        PathEntrySummary { max_id: self.id }
2021    }
2022}
2023
2024impl sum_tree::KeyedItem for PathEntry {
2025    type Key = ProjectEntryId;
2026
2027    fn key(&self) -> Self::Key {
2028        self.id
2029    }
2030}
2031
2032#[derive(Clone, Debug, Default)]
2033struct PathEntrySummary {
2034    max_id: ProjectEntryId,
2035}
2036
2037impl sum_tree::Summary for PathEntrySummary {
2038    type Context = ();
2039
2040    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2041        self.max_id = summary.max_id;
2042    }
2043}
2044
2045impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2046    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2047        *self = summary.max_id;
2048    }
2049}
2050
2051#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2052pub struct PathKey(Arc<Path>);
2053
2054impl Default for PathKey {
2055    fn default() -> Self {
2056        Self(Path::new("").into())
2057    }
2058}
2059
2060impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2061    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2062        self.0 = summary.max_path.clone();
2063    }
2064}
2065
2066struct BackgroundScanner {
2067    fs: Arc<dyn Fs>,
2068    snapshot: Arc<Mutex<LocalSnapshot>>,
2069    notify: UnboundedSender<ScanState>,
2070    executor: Arc<executor::Background>,
2071}
2072
2073impl BackgroundScanner {
2074    fn new(
2075        snapshot: Arc<Mutex<LocalSnapshot>>,
2076        notify: UnboundedSender<ScanState>,
2077        fs: Arc<dyn Fs>,
2078        executor: Arc<executor::Background>,
2079    ) -> Self {
2080        Self {
2081            fs,
2082            snapshot,
2083            notify,
2084            executor,
2085        }
2086    }
2087
2088    fn abs_path(&self) -> Arc<Path> {
2089        self.snapshot.lock().abs_path.clone()
2090    }
2091
2092    fn snapshot(&self) -> LocalSnapshot {
2093        self.snapshot.lock().clone()
2094    }
2095
2096    async fn run(mut self, events_rx: impl Stream<Item = Vec<fsevent::Event>>) {
2097        if self.notify.unbounded_send(ScanState::Scanning).is_err() {
2098            return;
2099        }
2100
2101        if let Err(err) = self.scan_dirs().await {
2102            if self
2103                .notify
2104                .unbounded_send(ScanState::Err(Arc::new(err)))
2105                .is_err()
2106            {
2107                return;
2108            }
2109        }
2110
2111        if self.notify.unbounded_send(ScanState::Idle).is_err() {
2112            return;
2113        }
2114
2115        futures::pin_mut!(events_rx);
2116        while let Some(events) = events_rx.next().await {
2117            if self.notify.unbounded_send(ScanState::Scanning).is_err() {
2118                break;
2119            }
2120
2121            if !self.process_events(events).await {
2122                break;
2123            }
2124
2125            if self.notify.unbounded_send(ScanState::Idle).is_err() {
2126                break;
2127            }
2128        }
2129    }
2130
2131    async fn scan_dirs(&mut self) -> Result<()> {
2132        let root_char_bag;
2133        let next_entry_id;
2134        let is_dir;
2135        {
2136            let snapshot = self.snapshot.lock();
2137            root_char_bag = snapshot.root_char_bag;
2138            next_entry_id = snapshot.next_entry_id.clone();
2139            is_dir = snapshot.root_entry().map_or(false, |e| e.is_dir())
2140        };
2141
2142        if is_dir {
2143            let path: Arc<Path> = Arc::from(Path::new(""));
2144            let abs_path = self.abs_path();
2145            let (tx, rx) = channel::unbounded();
2146            self.executor
2147                .block(tx.send(ScanJob {
2148                    abs_path: abs_path.to_path_buf(),
2149                    path,
2150                    ignore_stack: IgnoreStack::none(),
2151                    scan_queue: tx.clone(),
2152                }))
2153                .unwrap();
2154            drop(tx);
2155
2156            self.executor
2157                .scoped(|scope| {
2158                    for _ in 0..self.executor.num_cpus() {
2159                        scope.spawn(async {
2160                            while let Ok(job) = rx.recv().await {
2161                                if let Err(err) = self
2162                                    .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2163                                    .await
2164                                {
2165                                    log::error!("error scanning {:?}: {}", job.abs_path, err);
2166                                }
2167                            }
2168                        });
2169                    }
2170                })
2171                .await;
2172        }
2173
2174        Ok(())
2175    }
2176
2177    async fn scan_dir(
2178        &self,
2179        root_char_bag: CharBag,
2180        next_entry_id: Arc<AtomicUsize>,
2181        job: &ScanJob,
2182    ) -> Result<()> {
2183        let mut new_entries: Vec<Entry> = Vec::new();
2184        let mut new_jobs: Vec<ScanJob> = Vec::new();
2185        let mut ignore_stack = job.ignore_stack.clone();
2186        let mut new_ignore = None;
2187
2188        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2189        while let Some(child_abs_path) = child_paths.next().await {
2190            let child_abs_path = match child_abs_path {
2191                Ok(child_abs_path) => child_abs_path,
2192                Err(error) => {
2193                    log::error!("error processing entry {:?}", error);
2194                    continue;
2195                }
2196            };
2197            let child_name = child_abs_path.file_name().unwrap();
2198            let child_path: Arc<Path> = job.path.join(child_name).into();
2199            let child_metadata = match self.fs.metadata(&child_abs_path).await? {
2200                Some(metadata) => metadata,
2201                None => continue,
2202            };
2203
2204            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2205            if child_name == *GITIGNORE {
2206                match build_gitignore(&child_abs_path, self.fs.as_ref()) {
2207                    Ok(ignore) => {
2208                        let ignore = Arc::new(ignore);
2209                        ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2210                        new_ignore = Some(ignore);
2211                    }
2212                    Err(error) => {
2213                        log::error!(
2214                            "error loading .gitignore file {:?} - {:?}",
2215                            child_name,
2216                            error
2217                        );
2218                    }
2219                }
2220
2221                // Update ignore status of any child entries we've already processed to reflect the
2222                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2223                // there should rarely be too numerous. Update the ignore stack associated with any
2224                // new jobs as well.
2225                let mut new_jobs = new_jobs.iter_mut();
2226                for entry in &mut new_entries {
2227                    entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2228                    if entry.is_dir() {
2229                        new_jobs.next().unwrap().ignore_stack = if entry.is_ignored {
2230                            IgnoreStack::all()
2231                        } else {
2232                            ignore_stack.clone()
2233                        };
2234                    }
2235                }
2236            }
2237
2238            let mut child_entry = Entry::new(
2239                child_path.clone(),
2240                &child_metadata,
2241                &next_entry_id,
2242                root_char_bag,
2243            );
2244
2245            if child_metadata.is_dir {
2246                let is_ignored = ignore_stack.is_path_ignored(&child_path, true);
2247                child_entry.is_ignored = is_ignored;
2248                new_entries.push(child_entry);
2249                new_jobs.push(ScanJob {
2250                    abs_path: child_abs_path,
2251                    path: child_path,
2252                    ignore_stack: if is_ignored {
2253                        IgnoreStack::all()
2254                    } else {
2255                        ignore_stack.clone()
2256                    },
2257                    scan_queue: job.scan_queue.clone(),
2258                });
2259            } else {
2260                child_entry.is_ignored = ignore_stack.is_path_ignored(&child_path, false);
2261                new_entries.push(child_entry);
2262            };
2263        }
2264
2265        self.snapshot
2266            .lock()
2267            .populate_dir(job.path.clone(), new_entries, new_ignore);
2268        for new_job in new_jobs {
2269            job.scan_queue.send(new_job).await.unwrap();
2270        }
2271
2272        Ok(())
2273    }
2274
2275    async fn process_events(&mut self, mut events: Vec<fsevent::Event>) -> bool {
2276        events.sort_unstable_by(|a, b| a.path.cmp(&b.path));
2277        events.dedup_by(|a, b| a.path.starts_with(&b.path));
2278
2279        let root_char_bag;
2280        let root_abs_path;
2281        let next_entry_id;
2282        {
2283            let snapshot = self.snapshot.lock();
2284            root_char_bag = snapshot.root_char_bag;
2285            root_abs_path = snapshot.abs_path.clone();
2286            next_entry_id = snapshot.next_entry_id.clone();
2287        }
2288
2289        let root_abs_path = if let Ok(abs_path) = self.fs.canonicalize(&root_abs_path).await {
2290            abs_path
2291        } else {
2292            return false;
2293        };
2294        let metadata = futures::future::join_all(
2295            events
2296                .iter()
2297                .map(|event| self.fs.metadata(&event.path))
2298                .collect::<Vec<_>>(),
2299        )
2300        .await;
2301
2302        // Hold the snapshot lock while clearing and re-inserting the root entries
2303        // for each event. This way, the snapshot is not observable to the foreground
2304        // thread while this operation is in-progress.
2305        let (scan_queue_tx, scan_queue_rx) = channel::unbounded();
2306        {
2307            let mut snapshot = self.snapshot.lock();
2308            snapshot.scan_id += 1;
2309            for event in &events {
2310                if let Ok(path) = event.path.strip_prefix(&root_abs_path) {
2311                    snapshot.remove_path(&path);
2312                }
2313            }
2314
2315            for (event, metadata) in events.into_iter().zip(metadata.into_iter()) {
2316                let path: Arc<Path> = match event.path.strip_prefix(&root_abs_path) {
2317                    Ok(path) => Arc::from(path.to_path_buf()),
2318                    Err(_) => {
2319                        log::error!(
2320                            "unexpected event {:?} for root path {:?}",
2321                            event.path,
2322                            root_abs_path
2323                        );
2324                        continue;
2325                    }
2326                };
2327
2328                match metadata {
2329                    Ok(Some(metadata)) => {
2330                        let ignore_stack = snapshot.ignore_stack_for_path(&path, metadata.is_dir);
2331                        let mut fs_entry = Entry::new(
2332                            path.clone(),
2333                            &metadata,
2334                            snapshot.next_entry_id.as_ref(),
2335                            snapshot.root_char_bag,
2336                        );
2337                        fs_entry.is_ignored = ignore_stack.is_all();
2338                        snapshot.insert_entry(fs_entry, self.fs.as_ref());
2339                        if metadata.is_dir {
2340                            self.executor
2341                                .block(scan_queue_tx.send(ScanJob {
2342                                    abs_path: event.path,
2343                                    path,
2344                                    ignore_stack,
2345                                    scan_queue: scan_queue_tx.clone(),
2346                                }))
2347                                .unwrap();
2348                        }
2349                    }
2350                    Ok(None) => {}
2351                    Err(err) => {
2352                        // TODO - create a special 'error' entry in the entries tree to mark this
2353                        log::error!("error reading file on event {:?}", err);
2354                    }
2355                }
2356            }
2357            drop(scan_queue_tx);
2358        }
2359
2360        // Scan any directories that were created as part of this event batch.
2361        self.executor
2362            .scoped(|scope| {
2363                for _ in 0..self.executor.num_cpus() {
2364                    scope.spawn(async {
2365                        while let Ok(job) = scan_queue_rx.recv().await {
2366                            if let Err(err) = self
2367                                .scan_dir(root_char_bag, next_entry_id.clone(), &job)
2368                                .await
2369                            {
2370                                log::error!("error scanning {:?}: {}", job.abs_path, err);
2371                            }
2372                        }
2373                    });
2374                }
2375            })
2376            .await;
2377
2378        // Attempt to detect renames only over a single batch of file-system events.
2379        self.snapshot.lock().removed_entry_ids.clear();
2380
2381        self.update_ignore_statuses().await;
2382        true
2383    }
2384
2385    async fn update_ignore_statuses(&self) {
2386        let mut snapshot = self.snapshot();
2387
2388        let mut ignores_to_update = Vec::new();
2389        let mut ignores_to_delete = Vec::new();
2390        for (parent_path, (_, scan_id)) in &snapshot.ignores {
2391            if *scan_id == snapshot.scan_id && snapshot.entry_for_path(parent_path).is_some() {
2392                ignores_to_update.push(parent_path.clone());
2393            }
2394
2395            let ignore_path = parent_path.join(&*GITIGNORE);
2396            if snapshot.entry_for_path(ignore_path).is_none() {
2397                ignores_to_delete.push(parent_path.clone());
2398            }
2399        }
2400
2401        for parent_path in ignores_to_delete {
2402            snapshot.ignores.remove(&parent_path);
2403            self.snapshot.lock().ignores.remove(&parent_path);
2404        }
2405
2406        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2407        ignores_to_update.sort_unstable();
2408        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2409        while let Some(parent_path) = ignores_to_update.next() {
2410            while ignores_to_update
2411                .peek()
2412                .map_or(false, |p| p.starts_with(&parent_path))
2413            {
2414                ignores_to_update.next().unwrap();
2415            }
2416
2417            let ignore_stack = snapshot.ignore_stack_for_path(&parent_path, true);
2418            ignore_queue_tx
2419                .send(UpdateIgnoreStatusJob {
2420                    path: parent_path,
2421                    ignore_stack,
2422                    ignore_queue: ignore_queue_tx.clone(),
2423                })
2424                .await
2425                .unwrap();
2426        }
2427        drop(ignore_queue_tx);
2428
2429        self.executor
2430            .scoped(|scope| {
2431                for _ in 0..self.executor.num_cpus() {
2432                    scope.spawn(async {
2433                        while let Ok(job) = ignore_queue_rx.recv().await {
2434                            self.update_ignore_status(job, &snapshot).await;
2435                        }
2436                    });
2437                }
2438            })
2439            .await;
2440    }
2441
2442    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2443        let mut ignore_stack = job.ignore_stack;
2444        if let Some((ignore, _)) = snapshot.ignores.get(&job.path) {
2445            ignore_stack = ignore_stack.append(job.path.clone(), ignore.clone());
2446        }
2447
2448        let mut entries_by_id_edits = Vec::new();
2449        let mut entries_by_path_edits = Vec::new();
2450        for mut entry in snapshot.child_entries(&job.path).cloned() {
2451            let was_ignored = entry.is_ignored;
2452            entry.is_ignored = ignore_stack.is_path_ignored(&entry.path, entry.is_dir());
2453            if entry.is_dir() {
2454                let child_ignore_stack = if entry.is_ignored {
2455                    IgnoreStack::all()
2456                } else {
2457                    ignore_stack.clone()
2458                };
2459                job.ignore_queue
2460                    .send(UpdateIgnoreStatusJob {
2461                        path: entry.path.clone(),
2462                        ignore_stack: child_ignore_stack,
2463                        ignore_queue: job.ignore_queue.clone(),
2464                    })
2465                    .await
2466                    .unwrap();
2467            }
2468
2469            if entry.is_ignored != was_ignored {
2470                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2471                path_entry.scan_id = snapshot.scan_id;
2472                path_entry.is_ignored = entry.is_ignored;
2473                entries_by_id_edits.push(Edit::Insert(path_entry));
2474                entries_by_path_edits.push(Edit::Insert(entry));
2475            }
2476        }
2477
2478        let mut snapshot = self.snapshot.lock();
2479        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2480        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2481    }
2482}
2483
2484fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
2485    let mut result = root_char_bag;
2486    result.extend(
2487        path.to_string_lossy()
2488            .chars()
2489            .map(|c| c.to_ascii_lowercase()),
2490    );
2491    result
2492}
2493
2494struct ScanJob {
2495    abs_path: PathBuf,
2496    path: Arc<Path>,
2497    ignore_stack: Arc<IgnoreStack>,
2498    scan_queue: Sender<ScanJob>,
2499}
2500
2501struct UpdateIgnoreStatusJob {
2502    path: Arc<Path>,
2503    ignore_stack: Arc<IgnoreStack>,
2504    ignore_queue: Sender<UpdateIgnoreStatusJob>,
2505}
2506
2507pub trait WorktreeHandle {
2508    #[cfg(any(test, feature = "test-support"))]
2509    fn flush_fs_events<'a>(
2510        &self,
2511        cx: &'a gpui::TestAppContext,
2512    ) -> futures::future::LocalBoxFuture<'a, ()>;
2513}
2514
2515impl WorktreeHandle for ModelHandle<Worktree> {
2516    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
2517    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
2518    // extra directory scans, and emit extra scan-state notifications.
2519    //
2520    // This function mutates the worktree's directory and waits for those mutations to be picked up,
2521    // to ensure that all redundant FS events have already been processed.
2522    #[cfg(any(test, feature = "test-support"))]
2523    fn flush_fs_events<'a>(
2524        &self,
2525        cx: &'a gpui::TestAppContext,
2526    ) -> futures::future::LocalBoxFuture<'a, ()> {
2527        use smol::future::FutureExt;
2528
2529        let filename = "fs-event-sentinel";
2530        let tree = self.clone();
2531        let (fs, root_path) = self.read_with(cx, |tree, _| {
2532            let tree = tree.as_local().unwrap();
2533            (tree.fs.clone(), tree.abs_path().clone())
2534        });
2535
2536        async move {
2537            fs.create_file(&root_path.join(filename), Default::default())
2538                .await
2539                .unwrap();
2540            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_some())
2541                .await;
2542
2543            fs.remove_file(&root_path.join(filename), Default::default())
2544                .await
2545                .unwrap();
2546            tree.condition(&cx, |tree, _| tree.entry_for_path(filename).is_none())
2547                .await;
2548
2549            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2550                .await;
2551        }
2552        .boxed_local()
2553    }
2554}
2555
2556#[derive(Clone, Debug)]
2557struct TraversalProgress<'a> {
2558    max_path: &'a Path,
2559    count: usize,
2560    visible_count: usize,
2561    file_count: usize,
2562    visible_file_count: usize,
2563}
2564
2565impl<'a> TraversalProgress<'a> {
2566    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
2567        match (include_ignored, include_dirs) {
2568            (true, true) => self.count,
2569            (true, false) => self.file_count,
2570            (false, true) => self.visible_count,
2571            (false, false) => self.visible_file_count,
2572        }
2573    }
2574}
2575
2576impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
2577    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2578        self.max_path = summary.max_path.as_ref();
2579        self.count += summary.count;
2580        self.visible_count += summary.visible_count;
2581        self.file_count += summary.file_count;
2582        self.visible_file_count += summary.visible_file_count;
2583    }
2584}
2585
2586impl<'a> Default for TraversalProgress<'a> {
2587    fn default() -> Self {
2588        Self {
2589            max_path: Path::new(""),
2590            count: 0,
2591            visible_count: 0,
2592            file_count: 0,
2593            visible_file_count: 0,
2594        }
2595    }
2596}
2597
2598pub struct Traversal<'a> {
2599    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
2600    include_ignored: bool,
2601    include_dirs: bool,
2602}
2603
2604impl<'a> Traversal<'a> {
2605    pub fn advance(&mut self) -> bool {
2606        self.advance_to_offset(self.offset() + 1)
2607    }
2608
2609    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
2610        self.cursor.seek_forward(
2611            &TraversalTarget::Count {
2612                count: offset,
2613                include_dirs: self.include_dirs,
2614                include_ignored: self.include_ignored,
2615            },
2616            Bias::Right,
2617            &(),
2618        )
2619    }
2620
2621    pub fn advance_to_sibling(&mut self) -> bool {
2622        while let Some(entry) = self.cursor.item() {
2623            self.cursor.seek_forward(
2624                &TraversalTarget::PathSuccessor(&entry.path),
2625                Bias::Left,
2626                &(),
2627            );
2628            if let Some(entry) = self.cursor.item() {
2629                if (self.include_dirs || !entry.is_dir())
2630                    && (self.include_ignored || !entry.is_ignored)
2631                {
2632                    return true;
2633                }
2634            }
2635        }
2636        false
2637    }
2638
2639    pub fn entry(&self) -> Option<&'a Entry> {
2640        self.cursor.item()
2641    }
2642
2643    pub fn offset(&self) -> usize {
2644        self.cursor
2645            .start()
2646            .count(self.include_dirs, self.include_ignored)
2647    }
2648}
2649
2650impl<'a> Iterator for Traversal<'a> {
2651    type Item = &'a Entry;
2652
2653    fn next(&mut self) -> Option<Self::Item> {
2654        if let Some(item) = self.entry() {
2655            self.advance();
2656            Some(item)
2657        } else {
2658            None
2659        }
2660    }
2661}
2662
2663#[derive(Debug)]
2664enum TraversalTarget<'a> {
2665    Path(&'a Path),
2666    PathSuccessor(&'a Path),
2667    Count {
2668        count: usize,
2669        include_ignored: bool,
2670        include_dirs: bool,
2671    },
2672}
2673
2674impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
2675    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
2676        match self {
2677            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
2678            TraversalTarget::PathSuccessor(path) => {
2679                if !cursor_location.max_path.starts_with(path) {
2680                    Ordering::Equal
2681                } else {
2682                    Ordering::Greater
2683                }
2684            }
2685            TraversalTarget::Count {
2686                count,
2687                include_dirs,
2688                include_ignored,
2689            } => Ord::cmp(
2690                count,
2691                &cursor_location.count(*include_dirs, *include_ignored),
2692            ),
2693        }
2694    }
2695}
2696
2697struct ChildEntriesIter<'a> {
2698    parent_path: &'a Path,
2699    traversal: Traversal<'a>,
2700}
2701
2702impl<'a> Iterator for ChildEntriesIter<'a> {
2703    type Item = &'a Entry;
2704
2705    fn next(&mut self) -> Option<Self::Item> {
2706        if let Some(item) = self.traversal.entry() {
2707            if item.path.starts_with(&self.parent_path) {
2708                self.traversal.advance_to_sibling();
2709                return Some(item);
2710            }
2711        }
2712        None
2713    }
2714}
2715
2716impl<'a> From<&'a Entry> for proto::Entry {
2717    fn from(entry: &'a Entry) -> Self {
2718        Self {
2719            id: entry.id.to_proto(),
2720            is_dir: entry.is_dir(),
2721            path: entry.path.as_os_str().as_bytes().to_vec(),
2722            inode: entry.inode,
2723            mtime: Some(entry.mtime.into()),
2724            is_symlink: entry.is_symlink,
2725            is_ignored: entry.is_ignored,
2726        }
2727    }
2728}
2729
2730impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
2731    type Error = anyhow::Error;
2732
2733    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
2734        if let Some(mtime) = entry.mtime {
2735            let kind = if entry.is_dir {
2736                EntryKind::Dir
2737            } else {
2738                let mut char_bag = root_char_bag.clone();
2739                char_bag.extend(
2740                    String::from_utf8_lossy(&entry.path)
2741                        .chars()
2742                        .map(|c| c.to_ascii_lowercase()),
2743                );
2744                EntryKind::File(char_bag)
2745            };
2746            let path: Arc<Path> = PathBuf::from(OsString::from_vec(entry.path)).into();
2747            Ok(Entry {
2748                id: ProjectEntryId::from_proto(entry.id),
2749                kind,
2750                path: path.clone(),
2751                inode: entry.inode,
2752                mtime: mtime.into(),
2753                is_symlink: entry.is_symlink,
2754                is_ignored: entry.is_ignored,
2755            })
2756        } else {
2757            Err(anyhow!(
2758                "missing mtime in remote worktree entry {:?}",
2759                entry.path
2760            ))
2761        }
2762    }
2763}
2764
2765#[cfg(test)]
2766mod tests {
2767    use super::*;
2768    use crate::fs::FakeFs;
2769    use anyhow::Result;
2770    use client::test::FakeHttpClient;
2771    use fs::RealFs;
2772    use gpui::TestAppContext;
2773    use rand::prelude::*;
2774    use serde_json::json;
2775    use std::{
2776        env,
2777        fmt::Write,
2778        time::{SystemTime, UNIX_EPOCH},
2779    };
2780    use util::test::temp_tree;
2781
2782    #[gpui::test]
2783    async fn test_traversal(cx: &mut TestAppContext) {
2784        let fs = FakeFs::new(cx.background());
2785        fs.insert_tree(
2786            "/root",
2787            json!({
2788               ".gitignore": "a/b\n",
2789               "a": {
2790                   "b": "",
2791                   "c": "",
2792               }
2793            }),
2794        )
2795        .await;
2796
2797        let http_client = FakeHttpClient::with_404_response();
2798        let client = Client::new(http_client);
2799
2800        let tree = Worktree::local(
2801            client,
2802            Arc::from(Path::new("/root")),
2803            true,
2804            fs,
2805            Default::default(),
2806            &mut cx.to_async(),
2807        )
2808        .await
2809        .unwrap();
2810        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2811            .await;
2812
2813        tree.read_with(cx, |tree, _| {
2814            assert_eq!(
2815                tree.entries(false)
2816                    .map(|entry| entry.path.as_ref())
2817                    .collect::<Vec<_>>(),
2818                vec![
2819                    Path::new(""),
2820                    Path::new(".gitignore"),
2821                    Path::new("a"),
2822                    Path::new("a/c"),
2823                ]
2824            );
2825            assert_eq!(
2826                tree.entries(true)
2827                    .map(|entry| entry.path.as_ref())
2828                    .collect::<Vec<_>>(),
2829                vec![
2830                    Path::new(""),
2831                    Path::new(".gitignore"),
2832                    Path::new("a"),
2833                    Path::new("a/b"),
2834                    Path::new("a/c"),
2835                ]
2836            );
2837        })
2838    }
2839
2840    #[gpui::test]
2841    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
2842        let dir = temp_tree(json!({
2843            ".git": {},
2844            ".gitignore": "ignored-dir\n",
2845            "tracked-dir": {
2846                "tracked-file1": "tracked contents",
2847            },
2848            "ignored-dir": {
2849                "ignored-file1": "ignored contents",
2850            }
2851        }));
2852
2853        let http_client = FakeHttpClient::with_404_response();
2854        let client = Client::new(http_client.clone());
2855
2856        let tree = Worktree::local(
2857            client,
2858            dir.path(),
2859            true,
2860            Arc::new(RealFs),
2861            Default::default(),
2862            &mut cx.to_async(),
2863        )
2864        .await
2865        .unwrap();
2866        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2867            .await;
2868        tree.flush_fs_events(&cx).await;
2869        cx.read(|cx| {
2870            let tree = tree.read(cx);
2871            let tracked = tree.entry_for_path("tracked-dir/tracked-file1").unwrap();
2872            let ignored = tree.entry_for_path("ignored-dir/ignored-file1").unwrap();
2873            assert_eq!(tracked.is_ignored, false);
2874            assert_eq!(ignored.is_ignored, true);
2875        });
2876
2877        std::fs::write(dir.path().join("tracked-dir/tracked-file2"), "").unwrap();
2878        std::fs::write(dir.path().join("ignored-dir/ignored-file2"), "").unwrap();
2879        tree.flush_fs_events(&cx).await;
2880        cx.read(|cx| {
2881            let tree = tree.read(cx);
2882            let dot_git = tree.entry_for_path(".git").unwrap();
2883            let tracked = tree.entry_for_path("tracked-dir/tracked-file2").unwrap();
2884            let ignored = tree.entry_for_path("ignored-dir/ignored-file2").unwrap();
2885            assert_eq!(tracked.is_ignored, false);
2886            assert_eq!(ignored.is_ignored, true);
2887            assert_eq!(dot_git.is_ignored, true);
2888        });
2889    }
2890
2891    #[gpui::test]
2892    async fn test_write_file(cx: &mut TestAppContext) {
2893        let dir = temp_tree(json!({
2894            ".git": {},
2895            ".gitignore": "ignored-dir\n",
2896            "tracked-dir": {},
2897            "ignored-dir": {}
2898        }));
2899
2900        let http_client = FakeHttpClient::with_404_response();
2901        let client = Client::new(http_client.clone());
2902
2903        let tree = Worktree::local(
2904            client,
2905            dir.path(),
2906            true,
2907            Arc::new(RealFs),
2908            Default::default(),
2909            &mut cx.to_async(),
2910        )
2911        .await
2912        .unwrap();
2913        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2914            .await;
2915        tree.flush_fs_events(&cx).await;
2916
2917        tree.update(cx, |tree, cx| {
2918            tree.as_local().unwrap().write_file(
2919                Path::new("tracked-dir/file.txt"),
2920                "hello".into(),
2921                cx,
2922            )
2923        })
2924        .await
2925        .unwrap();
2926        tree.update(cx, |tree, cx| {
2927            tree.as_local().unwrap().write_file(
2928                Path::new("ignored-dir/file.txt"),
2929                "world".into(),
2930                cx,
2931            )
2932        })
2933        .await
2934        .unwrap();
2935
2936        tree.read_with(cx, |tree, _| {
2937            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
2938            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
2939            assert_eq!(tracked.is_ignored, false);
2940            assert_eq!(ignored.is_ignored, true);
2941        });
2942    }
2943
2944    #[gpui::test(iterations = 100)]
2945    fn test_random(mut rng: StdRng) {
2946        let operations = env::var("OPERATIONS")
2947            .map(|o| o.parse().unwrap())
2948            .unwrap_or(40);
2949        let initial_entries = env::var("INITIAL_ENTRIES")
2950            .map(|o| o.parse().unwrap())
2951            .unwrap_or(20);
2952
2953        let root_dir = tempdir::TempDir::new("worktree-test").unwrap();
2954        for _ in 0..initial_entries {
2955            randomly_mutate_tree(root_dir.path(), 1.0, &mut rng).unwrap();
2956        }
2957        log::info!("Generated initial tree");
2958
2959        let (notify_tx, _notify_rx) = mpsc::unbounded();
2960        let fs = Arc::new(RealFs);
2961        let next_entry_id = Arc::new(AtomicUsize::new(0));
2962        let mut initial_snapshot = LocalSnapshot {
2963            abs_path: root_dir.path().into(),
2964            removed_entry_ids: Default::default(),
2965            ignores: Default::default(),
2966            next_entry_id: next_entry_id.clone(),
2967            snapshot: Snapshot {
2968                id: WorktreeId::from_usize(0),
2969                entries_by_path: Default::default(),
2970                entries_by_id: Default::default(),
2971                root_name: Default::default(),
2972                root_char_bag: Default::default(),
2973                scan_id: 0,
2974            },
2975        };
2976        initial_snapshot.insert_entry(
2977            Entry::new(
2978                Path::new("").into(),
2979                &smol::block_on(fs.metadata(root_dir.path()))
2980                    .unwrap()
2981                    .unwrap(),
2982                &next_entry_id,
2983                Default::default(),
2984            ),
2985            fs.as_ref(),
2986        );
2987        let mut scanner = BackgroundScanner::new(
2988            Arc::new(Mutex::new(initial_snapshot.clone())),
2989            notify_tx,
2990            fs.clone(),
2991            Arc::new(gpui::executor::Background::new()),
2992        );
2993        smol::block_on(scanner.scan_dirs()).unwrap();
2994        scanner.snapshot().check_invariants();
2995
2996        let mut events = Vec::new();
2997        let mut snapshots = Vec::new();
2998        let mut mutations_len = operations;
2999        while mutations_len > 1 {
3000            if !events.is_empty() && rng.gen_bool(0.4) {
3001                let len = rng.gen_range(0..=events.len());
3002                let to_deliver = events.drain(0..len).collect::<Vec<_>>();
3003                log::info!("Delivering events: {:#?}", to_deliver);
3004                smol::block_on(scanner.process_events(to_deliver));
3005                scanner.snapshot().check_invariants();
3006            } else {
3007                events.extend(randomly_mutate_tree(root_dir.path(), 0.6, &mut rng).unwrap());
3008                mutations_len -= 1;
3009            }
3010
3011            if rng.gen_bool(0.2) {
3012                snapshots.push(scanner.snapshot());
3013            }
3014        }
3015        log::info!("Quiescing: {:#?}", events);
3016        smol::block_on(scanner.process_events(events));
3017        scanner.snapshot().check_invariants();
3018
3019        let (notify_tx, _notify_rx) = mpsc::unbounded();
3020        let mut new_scanner = BackgroundScanner::new(
3021            Arc::new(Mutex::new(initial_snapshot)),
3022            notify_tx,
3023            scanner.fs.clone(),
3024            scanner.executor.clone(),
3025        );
3026        smol::block_on(new_scanner.scan_dirs()).unwrap();
3027        assert_eq!(
3028            scanner.snapshot().to_vec(true),
3029            new_scanner.snapshot().to_vec(true)
3030        );
3031
3032        for mut prev_snapshot in snapshots {
3033            let include_ignored = rng.gen::<bool>();
3034            if !include_ignored {
3035                let mut entries_by_path_edits = Vec::new();
3036                let mut entries_by_id_edits = Vec::new();
3037                for entry in prev_snapshot
3038                    .entries_by_id
3039                    .cursor::<()>()
3040                    .filter(|e| e.is_ignored)
3041                {
3042                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
3043                    entries_by_id_edits.push(Edit::Remove(entry.id));
3044                }
3045
3046                prev_snapshot
3047                    .entries_by_path
3048                    .edit(entries_by_path_edits, &());
3049                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
3050            }
3051
3052            let update = scanner
3053                .snapshot()
3054                .build_update(&prev_snapshot, 0, 0, include_ignored);
3055            prev_snapshot.apply_remote_update(update).unwrap();
3056            assert_eq!(
3057                prev_snapshot.to_vec(true),
3058                scanner.snapshot().to_vec(include_ignored)
3059            );
3060        }
3061    }
3062
3063    fn randomly_mutate_tree(
3064        root_path: &Path,
3065        insertion_probability: f64,
3066        rng: &mut impl Rng,
3067    ) -> Result<Vec<fsevent::Event>> {
3068        let root_path = root_path.canonicalize().unwrap();
3069        let (dirs, files) = read_dir_recursive(root_path.clone());
3070
3071        let mut events = Vec::new();
3072        let mut record_event = |path: PathBuf| {
3073            events.push(fsevent::Event {
3074                event_id: SystemTime::now()
3075                    .duration_since(UNIX_EPOCH)
3076                    .unwrap()
3077                    .as_secs(),
3078                flags: fsevent::StreamFlags::empty(),
3079                path,
3080            });
3081        };
3082
3083        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
3084            let path = dirs.choose(rng).unwrap();
3085            let new_path = path.join(gen_name(rng));
3086
3087            if rng.gen() {
3088                log::info!("Creating dir {:?}", new_path.strip_prefix(root_path)?);
3089                std::fs::create_dir(&new_path)?;
3090            } else {
3091                log::info!("Creating file {:?}", new_path.strip_prefix(root_path)?);
3092                std::fs::write(&new_path, "")?;
3093            }
3094            record_event(new_path);
3095        } else if rng.gen_bool(0.05) {
3096            let ignore_dir_path = dirs.choose(rng).unwrap();
3097            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
3098
3099            let (subdirs, subfiles) = read_dir_recursive(ignore_dir_path.clone());
3100            let files_to_ignore = {
3101                let len = rng.gen_range(0..=subfiles.len());
3102                subfiles.choose_multiple(rng, len)
3103            };
3104            let dirs_to_ignore = {
3105                let len = rng.gen_range(0..subdirs.len());
3106                subdirs.choose_multiple(rng, len)
3107            };
3108
3109            let mut ignore_contents = String::new();
3110            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
3111                write!(
3112                    ignore_contents,
3113                    "{}\n",
3114                    path_to_ignore
3115                        .strip_prefix(&ignore_dir_path)?
3116                        .to_str()
3117                        .unwrap()
3118                )
3119                .unwrap();
3120            }
3121            log::info!(
3122                "Creating {:?} with contents:\n{}",
3123                ignore_path.strip_prefix(&root_path)?,
3124                ignore_contents
3125            );
3126            std::fs::write(&ignore_path, ignore_contents).unwrap();
3127            record_event(ignore_path);
3128        } else {
3129            let old_path = {
3130                let file_path = files.choose(rng);
3131                let dir_path = dirs[1..].choose(rng);
3132                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
3133            };
3134
3135            let is_rename = rng.gen();
3136            if is_rename {
3137                let new_path_parent = dirs
3138                    .iter()
3139                    .filter(|d| !d.starts_with(old_path))
3140                    .choose(rng)
3141                    .unwrap();
3142
3143                let overwrite_existing_dir =
3144                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
3145                let new_path = if overwrite_existing_dir {
3146                    std::fs::remove_dir_all(&new_path_parent).ok();
3147                    new_path_parent.to_path_buf()
3148                } else {
3149                    new_path_parent.join(gen_name(rng))
3150                };
3151
3152                log::info!(
3153                    "Renaming {:?} to {}{:?}",
3154                    old_path.strip_prefix(&root_path)?,
3155                    if overwrite_existing_dir {
3156                        "overwrite "
3157                    } else {
3158                        ""
3159                    },
3160                    new_path.strip_prefix(&root_path)?
3161                );
3162                std::fs::rename(&old_path, &new_path)?;
3163                record_event(old_path.clone());
3164                record_event(new_path);
3165            } else if old_path.is_dir() {
3166                let (dirs, files) = read_dir_recursive(old_path.clone());
3167
3168                log::info!("Deleting dir {:?}", old_path.strip_prefix(&root_path)?);
3169                std::fs::remove_dir_all(&old_path).unwrap();
3170                for file in files {
3171                    record_event(file);
3172                }
3173                for dir in dirs {
3174                    record_event(dir);
3175                }
3176            } else {
3177                log::info!("Deleting file {:?}", old_path.strip_prefix(&root_path)?);
3178                std::fs::remove_file(old_path).unwrap();
3179                record_event(old_path.clone());
3180            }
3181        }
3182
3183        Ok(events)
3184    }
3185
3186    fn read_dir_recursive(path: PathBuf) -> (Vec<PathBuf>, Vec<PathBuf>) {
3187        let child_entries = std::fs::read_dir(&path).unwrap();
3188        let mut dirs = vec![path];
3189        let mut files = Vec::new();
3190        for child_entry in child_entries {
3191            let child_path = child_entry.unwrap().path();
3192            if child_path.is_dir() {
3193                let (child_dirs, child_files) = read_dir_recursive(child_path);
3194                dirs.extend(child_dirs);
3195                files.extend(child_files);
3196            } else {
3197                files.push(child_path);
3198            }
3199        }
3200        (dirs, files)
3201    }
3202
3203    fn gen_name(rng: &mut impl Rng) -> String {
3204        (0..6)
3205            .map(|_| rng.sample(rand::distributions::Alphanumeric))
3206            .map(char::from)
3207            .collect()
3208    }
3209
3210    impl LocalSnapshot {
3211        fn check_invariants(&self) {
3212            let mut files = self.files(true, 0);
3213            let mut visible_files = self.files(false, 0);
3214            for entry in self.entries_by_path.cursor::<()>() {
3215                if entry.is_file() {
3216                    assert_eq!(files.next().unwrap().inode, entry.inode);
3217                    if !entry.is_ignored {
3218                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
3219                    }
3220                }
3221            }
3222            assert!(files.next().is_none());
3223            assert!(visible_files.next().is_none());
3224
3225            let mut bfs_paths = Vec::new();
3226            let mut stack = vec![Path::new("")];
3227            while let Some(path) = stack.pop() {
3228                bfs_paths.push(path);
3229                let ix = stack.len();
3230                for child_entry in self.child_entries(path) {
3231                    stack.insert(ix, &child_entry.path);
3232                }
3233            }
3234
3235            let dfs_paths_via_iter = self
3236                .entries_by_path
3237                .cursor::<()>()
3238                .map(|e| e.path.as_ref())
3239                .collect::<Vec<_>>();
3240            assert_eq!(bfs_paths, dfs_paths_via_iter);
3241
3242            let dfs_paths_via_traversal = self
3243                .entries(true)
3244                .map(|e| e.path.as_ref())
3245                .collect::<Vec<_>>();
3246            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
3247
3248            for (ignore_parent_path, _) in &self.ignores {
3249                assert!(self.entry_for_path(ignore_parent_path).is_some());
3250                assert!(self
3251                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
3252                    .is_some());
3253            }
3254        }
3255
3256        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
3257            let mut paths = Vec::new();
3258            for entry in self.entries_by_path.cursor::<()>() {
3259                if include_ignored || !entry.is_ignored {
3260                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
3261                }
3262            }
3263            paths.sort_by(|a, b| a.0.cmp(&b.0));
3264            paths
3265        }
3266    }
3267}