worktree.rs

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