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