worktree.rs

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