worktree.rs

   1use crate::{
   2    copy_recursive, ignore::IgnoreStack, DiagnosticSummary, ProjectEntryId, RemoveOptions,
   3};
   4use ::ignore::gitignore::{Gitignore, GitignoreBuilder};
   5use anyhow::{anyhow, Context, Result};
   6use client::{proto, Client};
   7use clock::ReplicaId;
   8use collections::{HashMap, VecDeque};
   9use fs::{repository::GitRepository, Fs, LineEnding};
  10use futures::{
  11    channel::{
  12        mpsc::{self, UnboundedSender},
  13        oneshot,
  14    },
  15    select_biased,
  16    task::Poll,
  17    Stream, StreamExt,
  18};
  19use fuzzy::CharBag;
  20use git::{DOT_GIT, GITIGNORE};
  21use gpui::{executor, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task};
  22use language::{
  23    proto::{
  24        deserialize_fingerprint, deserialize_version, serialize_fingerprint, serialize_line_ending,
  25        serialize_version,
  26    },
  27    Buffer, DiagnosticEntry, File as _, PointUtf16, Rope, RopeFingerprint, Unclipped,
  28};
  29use lsp::LanguageServerId;
  30use parking_lot::Mutex;
  31use postage::{
  32    barrier,
  33    prelude::{Sink as _, Stream as _},
  34    watch,
  35};
  36use smol::channel::{self, Sender};
  37use std::{
  38    any::Any,
  39    cmp::{self, Ordering},
  40    convert::TryFrom,
  41    ffi::OsStr,
  42    fmt,
  43    future::Future,
  44    mem,
  45    ops::{Deref, DerefMut},
  46    path::{Path, PathBuf},
  47    pin::Pin,
  48    sync::{
  49        atomic::{AtomicUsize, Ordering::SeqCst},
  50        Arc,
  51    },
  52    time::{Duration, SystemTime},
  53};
  54use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
  55use util::{paths::HOME, ResultExt, TryFutureExt};
  56
  57#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
  58pub struct WorktreeId(usize);
  59
  60pub enum Worktree {
  61    Local(LocalWorktree),
  62    Remote(RemoteWorktree),
  63}
  64
  65pub struct LocalWorktree {
  66    snapshot: LocalSnapshot,
  67    path_changes_tx: channel::Sender<(Vec<PathBuf>, barrier::Sender)>,
  68    is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
  69    _background_scanner_task: Task<()>,
  70    share: Option<ShareState>,
  71    diagnostics: HashMap<
  72        Arc<Path>,
  73        Vec<(
  74            LanguageServerId,
  75            Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
  76        )>,
  77    >,
  78    diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
  79    client: Arc<Client>,
  80    fs: Arc<dyn Fs>,
  81    visible: bool,
  82}
  83
  84pub struct RemoteWorktree {
  85    snapshot: Snapshot,
  86    background_snapshot: Arc<Mutex<Snapshot>>,
  87    project_id: u64,
  88    client: Arc<Client>,
  89    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
  90    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
  91    replica_id: ReplicaId,
  92    diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
  93    visible: bool,
  94    disconnected: bool,
  95}
  96
  97#[derive(Clone)]
  98pub struct Snapshot {
  99    id: WorktreeId,
 100    abs_path: Arc<Path>,
 101    root_name: String,
 102    root_char_bag: CharBag,
 103    entries_by_path: SumTree<Entry>,
 104    entries_by_id: SumTree<PathEntry>,
 105    repository_entries: TreeMap<RepositoryWorkDirectory, RepositoryEntry>,
 106
 107    /// A number that increases every time the worktree begins scanning
 108    /// a set of paths from the filesystem. This scanning could be caused
 109    /// by some operation performed on the worktree, such as reading or
 110    /// writing a file, or by an event reported by the filesystem.
 111    scan_id: usize,
 112
 113    /// The latest scan id that has completed, and whose preceding scans
 114    /// have all completed. The current `scan_id` could be more than one
 115    /// greater than the `completed_scan_id` if operations are performed
 116    /// on the worktree while it is processing a file-system event.
 117    completed_scan_id: usize,
 118}
 119
 120#[derive(Clone, Debug, Eq, PartialEq)]
 121pub struct RepositoryEntry {
 122    pub(crate) work_directory: WorkDirectoryEntry,
 123    pub(crate) branch: Option<Arc<str>>,
 124}
 125
 126impl RepositoryEntry {
 127    pub fn branch(&self) -> Option<Arc<str>> {
 128        self.branch.clone()
 129    }
 130
 131    pub fn work_directory_id(&self) -> ProjectEntryId {
 132        *self.work_directory
 133    }
 134
 135    pub fn work_directory(&self, snapshot: &Snapshot) -> Option<RepositoryWorkDirectory> {
 136        snapshot
 137            .entry_for_id(self.work_directory_id())
 138            .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
 139    }
 140
 141    pub(crate) fn contains(&self, snapshot: &Snapshot, path: &Path) -> bool {
 142        self.work_directory.contains(snapshot, path)
 143    }
 144}
 145
 146impl From<&RepositoryEntry> for proto::RepositoryEntry {
 147    fn from(value: &RepositoryEntry) -> Self {
 148        proto::RepositoryEntry {
 149            work_directory_id: value.work_directory.to_proto(),
 150            branch: value.branch.as_ref().map(|str| str.to_string()),
 151        }
 152    }
 153}
 154
 155/// This path corresponds to the 'content path' (the folder that contains the .git)
 156#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
 157pub struct RepositoryWorkDirectory(Arc<Path>);
 158
 159impl Default for RepositoryWorkDirectory {
 160    fn default() -> Self {
 161        RepositoryWorkDirectory(Arc::from(Path::new("")))
 162    }
 163}
 164
 165#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
 166pub struct WorkDirectoryEntry(ProjectEntryId);
 167
 168impl WorkDirectoryEntry {
 169    // Note that these paths should be relative to the worktree root.
 170    pub(crate) fn contains(&self, snapshot: &Snapshot, path: &Path) -> bool {
 171        snapshot
 172            .entry_for_id(self.0)
 173            .map(|entry| path.starts_with(&entry.path))
 174            .unwrap_or(false)
 175    }
 176
 177    pub(crate) fn relativize(&self, worktree: &Snapshot, path: &Path) -> Option<RepoPath> {
 178        worktree.entry_for_id(self.0).and_then(|entry| {
 179            path.strip_prefix(&entry.path)
 180                .ok()
 181                .map(move |path| RepoPath(path.to_owned()))
 182        })
 183    }
 184}
 185
 186impl Deref for WorkDirectoryEntry {
 187    type Target = ProjectEntryId;
 188
 189    fn deref(&self) -> &Self::Target {
 190        &self.0
 191    }
 192}
 193
 194impl<'a> From<ProjectEntryId> for WorkDirectoryEntry {
 195    fn from(value: ProjectEntryId) -> Self {
 196        WorkDirectoryEntry(value)
 197    }
 198}
 199
 200#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
 201pub struct RepoPath(PathBuf);
 202
 203impl AsRef<Path> for RepoPath {
 204    fn as_ref(&self) -> &Path {
 205        self.0.as_ref()
 206    }
 207}
 208
 209impl Deref for RepoPath {
 210    type Target = PathBuf;
 211
 212    fn deref(&self) -> &Self::Target {
 213        &self.0
 214    }
 215}
 216
 217impl AsRef<Path> for RepositoryWorkDirectory {
 218    fn as_ref(&self) -> &Path {
 219        self.0.as_ref()
 220    }
 221}
 222
 223#[derive(Debug, Clone)]
 224pub struct LocalSnapshot {
 225    ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, usize)>,
 226    // The ProjectEntryId corresponds to the entry for the .git dir
 227    // work_directory_id
 228    git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
 229    removed_entry_ids: HashMap<u64, ProjectEntryId>,
 230    next_entry_id: Arc<AtomicUsize>,
 231    snapshot: Snapshot,
 232}
 233
 234#[derive(Debug, Clone)]
 235pub struct LocalRepositoryEntry {
 236    pub(crate) scan_id: usize,
 237    pub(crate) repo_ptr: Arc<Mutex<dyn GitRepository>>,
 238    /// Path to the actual .git folder.
 239    /// Note: if .git is a file, this points to the folder indicated by the .git file
 240    pub(crate) git_dir_path: Arc<Path>,
 241}
 242
 243impl LocalRepositoryEntry {
 244    // Note that this path should be relative to the worktree root.
 245    pub(crate) fn in_dot_git(&self, path: &Path) -> bool {
 246        path.starts_with(self.git_dir_path.as_ref())
 247    }
 248}
 249
 250impl Deref for LocalSnapshot {
 251    type Target = Snapshot;
 252
 253    fn deref(&self) -> &Self::Target {
 254        &self.snapshot
 255    }
 256}
 257
 258impl DerefMut for LocalSnapshot {
 259    fn deref_mut(&mut self) -> &mut Self::Target {
 260        &mut self.snapshot
 261    }
 262}
 263
 264enum ScanState {
 265    Started,
 266    Updated {
 267        snapshot: LocalSnapshot,
 268        changes: HashMap<Arc<Path>, PathChange>,
 269        barrier: Option<barrier::Sender>,
 270        scanning: bool,
 271    },
 272}
 273
 274struct ShareState {
 275    project_id: u64,
 276    snapshots_tx: watch::Sender<LocalSnapshot>,
 277    resume_updates: watch::Sender<()>,
 278    _maintain_remote_snapshot: Task<Option<()>>,
 279}
 280
 281pub enum Event {
 282    UpdatedEntries(HashMap<Arc<Path>, PathChange>),
 283    UpdatedGitRepositories(HashMap<Arc<Path>, LocalRepositoryEntry>),
 284}
 285
 286impl Entity for Worktree {
 287    type Event = Event;
 288}
 289
 290impl Worktree {
 291    pub async fn local(
 292        client: Arc<Client>,
 293        path: impl Into<Arc<Path>>,
 294        visible: bool,
 295        fs: Arc<dyn Fs>,
 296        next_entry_id: Arc<AtomicUsize>,
 297        cx: &mut AsyncAppContext,
 298    ) -> Result<ModelHandle<Self>> {
 299        // After determining whether the root entry is a file or a directory, populate the
 300        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
 301        let abs_path = path.into();
 302        let metadata = fs
 303            .metadata(&abs_path)
 304            .await
 305            .context("failed to stat worktree path")?;
 306
 307        Ok(cx.add_model(move |cx: &mut ModelContext<Worktree>| {
 308            let root_name = abs_path
 309                .file_name()
 310                .map_or(String::new(), |f| f.to_string_lossy().to_string());
 311
 312            let mut snapshot = LocalSnapshot {
 313                ignores_by_parent_abs_path: Default::default(),
 314                removed_entry_ids: Default::default(),
 315                git_repositories: Default::default(),
 316                next_entry_id,
 317                snapshot: Snapshot {
 318                    id: WorktreeId::from_usize(cx.model_id()),
 319                    abs_path: abs_path.clone(),
 320                    root_name: root_name.clone(),
 321                    root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
 322                    entries_by_path: Default::default(),
 323                    entries_by_id: Default::default(),
 324                    repository_entries: Default::default(),
 325                    scan_id: 1,
 326                    completed_scan_id: 0,
 327                },
 328            };
 329
 330            if let Some(metadata) = metadata {
 331                snapshot.insert_entry(
 332                    Entry::new(
 333                        Arc::from(Path::new("")),
 334                        &metadata,
 335                        &snapshot.next_entry_id,
 336                        snapshot.root_char_bag,
 337                    ),
 338                    fs.as_ref(),
 339                );
 340            }
 341
 342            let (path_changes_tx, path_changes_rx) = channel::unbounded();
 343            let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
 344
 345            cx.spawn_weak(|this, mut cx| async move {
 346                while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade(&cx)) {
 347                    this.update(&mut cx, |this, cx| {
 348                        let this = this.as_local_mut().unwrap();
 349                        match state {
 350                            ScanState::Started => {
 351                                *this.is_scanning.0.borrow_mut() = true;
 352                            }
 353                            ScanState::Updated {
 354                                snapshot,
 355                                changes,
 356                                barrier,
 357                                scanning,
 358                            } => {
 359                                *this.is_scanning.0.borrow_mut() = scanning;
 360                                this.set_snapshot(snapshot, cx);
 361                                cx.emit(Event::UpdatedEntries(changes));
 362                                drop(barrier);
 363                            }
 364                        }
 365                        cx.notify();
 366                    });
 367                }
 368            })
 369            .detach();
 370
 371            let background_scanner_task = cx.background().spawn({
 372                let fs = fs.clone();
 373                let snapshot = snapshot.clone();
 374                let background = cx.background().clone();
 375                async move {
 376                    let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
 377                    BackgroundScanner::new(
 378                        snapshot,
 379                        fs,
 380                        scan_states_tx,
 381                        background,
 382                        path_changes_rx,
 383                    )
 384                    .run(events)
 385                    .await;
 386                }
 387            });
 388
 389            Worktree::Local(LocalWorktree {
 390                snapshot,
 391                is_scanning: watch::channel_with(true),
 392                share: None,
 393                path_changes_tx,
 394                _background_scanner_task: background_scanner_task,
 395                diagnostics: Default::default(),
 396                diagnostic_summaries: Default::default(),
 397                client,
 398                fs,
 399                visible,
 400            })
 401        }))
 402    }
 403
 404    pub fn remote(
 405        project_remote_id: u64,
 406        replica_id: ReplicaId,
 407        worktree: proto::WorktreeMetadata,
 408        client: Arc<Client>,
 409        cx: &mut AppContext,
 410    ) -> ModelHandle<Self> {
 411        cx.add_model(|cx: &mut ModelContext<Self>| {
 412            let snapshot = Snapshot {
 413                id: WorktreeId(worktree.id as usize),
 414                abs_path: Arc::from(PathBuf::from(worktree.abs_path)),
 415                root_name: worktree.root_name.clone(),
 416                root_char_bag: worktree
 417                    .root_name
 418                    .chars()
 419                    .map(|c| c.to_ascii_lowercase())
 420                    .collect(),
 421                entries_by_path: Default::default(),
 422                entries_by_id: Default::default(),
 423                repository_entries: Default::default(),
 424                scan_id: 1,
 425                completed_scan_id: 0,
 426            };
 427
 428            let (updates_tx, mut updates_rx) = mpsc::unbounded();
 429            let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
 430            let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 431
 432            cx.background()
 433                .spawn({
 434                    let background_snapshot = background_snapshot.clone();
 435                    async move {
 436                        while let Some(update) = updates_rx.next().await {
 437                            if let Err(error) =
 438                                background_snapshot.lock().apply_remote_update(update)
 439                            {
 440                                log::error!("error applying worktree update: {}", error);
 441                            }
 442                            snapshot_updated_tx.send(()).await.ok();
 443                        }
 444                    }
 445                })
 446                .detach();
 447
 448            cx.spawn_weak(|this, mut cx| async move {
 449                while (snapshot_updated_rx.recv().await).is_some() {
 450                    if let Some(this) = this.upgrade(&cx) {
 451                        this.update(&mut cx, |this, cx| {
 452                            let this = this.as_remote_mut().unwrap();
 453                            this.snapshot = this.background_snapshot.lock().clone();
 454                            cx.emit(Event::UpdatedEntries(Default::default()));
 455                            cx.notify();
 456                            while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 457                                if this.observed_snapshot(*scan_id) {
 458                                    let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 459                                    let _ = tx.send(());
 460                                } else {
 461                                    break;
 462                                }
 463                            }
 464                        });
 465                    } else {
 466                        break;
 467                    }
 468                }
 469            })
 470            .detach();
 471
 472            Worktree::Remote(RemoteWorktree {
 473                project_id: project_remote_id,
 474                replica_id,
 475                snapshot: snapshot.clone(),
 476                background_snapshot,
 477                updates_tx: Some(updates_tx),
 478                snapshot_subscriptions: Default::default(),
 479                client: client.clone(),
 480                diagnostic_summaries: Default::default(),
 481                visible: worktree.visible,
 482                disconnected: false,
 483            })
 484        })
 485    }
 486
 487    pub fn as_local(&self) -> Option<&LocalWorktree> {
 488        if let Worktree::Local(worktree) = self {
 489            Some(worktree)
 490        } else {
 491            None
 492        }
 493    }
 494
 495    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 496        if let Worktree::Remote(worktree) = self {
 497            Some(worktree)
 498        } else {
 499            None
 500        }
 501    }
 502
 503    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 504        if let Worktree::Local(worktree) = self {
 505            Some(worktree)
 506        } else {
 507            None
 508        }
 509    }
 510
 511    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 512        if let Worktree::Remote(worktree) = self {
 513            Some(worktree)
 514        } else {
 515            None
 516        }
 517    }
 518
 519    pub fn is_local(&self) -> bool {
 520        matches!(self, Worktree::Local(_))
 521    }
 522
 523    pub fn is_remote(&self) -> bool {
 524        !self.is_local()
 525    }
 526
 527    pub fn snapshot(&self) -> Snapshot {
 528        match self {
 529            Worktree::Local(worktree) => worktree.snapshot().snapshot,
 530            Worktree::Remote(worktree) => worktree.snapshot(),
 531        }
 532    }
 533
 534    pub fn scan_id(&self) -> usize {
 535        match self {
 536            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 537            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 538        }
 539    }
 540
 541    pub fn completed_scan_id(&self) -> usize {
 542        match self {
 543            Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
 544            Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
 545        }
 546    }
 547
 548    pub fn is_visible(&self) -> bool {
 549        match self {
 550            Worktree::Local(worktree) => worktree.visible,
 551            Worktree::Remote(worktree) => worktree.visible,
 552        }
 553    }
 554
 555    pub fn replica_id(&self) -> ReplicaId {
 556        match self {
 557            Worktree::Local(_) => 0,
 558            Worktree::Remote(worktree) => worktree.replica_id,
 559        }
 560    }
 561
 562    pub fn diagnostic_summaries(
 563        &self,
 564    ) -> impl Iterator<Item = (Arc<Path>, LanguageServerId, DiagnosticSummary)> + '_ {
 565        match self {
 566            Worktree::Local(worktree) => &worktree.diagnostic_summaries,
 567            Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
 568        }
 569        .iter()
 570        .flat_map(|(path, summaries)| {
 571            summaries
 572                .iter()
 573                .map(move |(&server_id, &summary)| (path.clone(), server_id, summary))
 574        })
 575    }
 576
 577    pub fn abs_path(&self) -> Arc<Path> {
 578        match self {
 579            Worktree::Local(worktree) => worktree.abs_path.clone(),
 580            Worktree::Remote(worktree) => worktree.abs_path.clone(),
 581        }
 582    }
 583}
 584
 585impl LocalWorktree {
 586    pub fn contains_abs_path(&self, path: &Path) -> bool {
 587        path.starts_with(&self.abs_path)
 588    }
 589
 590    fn absolutize(&self, path: &Path) -> PathBuf {
 591        if path.file_name().is_some() {
 592            self.abs_path.join(path)
 593        } else {
 594            self.abs_path.to_path_buf()
 595        }
 596    }
 597
 598    pub(crate) fn load_buffer(
 599        &mut self,
 600        id: u64,
 601        path: &Path,
 602        cx: &mut ModelContext<Worktree>,
 603    ) -> Task<Result<ModelHandle<Buffer>>> {
 604        let path = Arc::from(path);
 605        cx.spawn(move |this, mut cx| async move {
 606            let (file, contents, diff_base) = this
 607                .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))
 608                .await?;
 609            let text_buffer = cx
 610                .background()
 611                .spawn(async move { text::Buffer::new(0, id, contents) })
 612                .await;
 613            Ok(cx.add_model(|cx| {
 614                let mut buffer = Buffer::build(text_buffer, diff_base, Some(Arc::new(file)));
 615                buffer.git_diff_recalc(cx);
 616                buffer
 617            }))
 618        })
 619    }
 620
 621    pub fn diagnostics_for_path(
 622        &self,
 623        path: &Path,
 624    ) -> Vec<(
 625        LanguageServerId,
 626        Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 627    )> {
 628        self.diagnostics.get(path).cloned().unwrap_or_default()
 629    }
 630
 631    pub fn update_diagnostics(
 632        &mut self,
 633        server_id: LanguageServerId,
 634        worktree_path: Arc<Path>,
 635        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 636        _: &mut ModelContext<Worktree>,
 637    ) -> Result<bool> {
 638        let summaries_by_server_id = self
 639            .diagnostic_summaries
 640            .entry(worktree_path.clone())
 641            .or_default();
 642
 643        let old_summary = summaries_by_server_id
 644            .remove(&server_id)
 645            .unwrap_or_default();
 646
 647        let new_summary = DiagnosticSummary::new(&diagnostics);
 648        if new_summary.is_empty() {
 649            if let Some(diagnostics_by_server_id) = self.diagnostics.get_mut(&worktree_path) {
 650                if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 651                    diagnostics_by_server_id.remove(ix);
 652                }
 653                if diagnostics_by_server_id.is_empty() {
 654                    self.diagnostics.remove(&worktree_path);
 655                }
 656            }
 657        } else {
 658            summaries_by_server_id.insert(server_id, new_summary);
 659            let diagnostics_by_server_id =
 660                self.diagnostics.entry(worktree_path.clone()).or_default();
 661            match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 662                Ok(ix) => {
 663                    diagnostics_by_server_id[ix] = (server_id, diagnostics);
 664                }
 665                Err(ix) => {
 666                    diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
 667                }
 668            }
 669        }
 670
 671        if !old_summary.is_empty() || !new_summary.is_empty() {
 672            if let Some(share) = self.share.as_ref() {
 673                self.client
 674                    .send(proto::UpdateDiagnosticSummary {
 675                        project_id: share.project_id,
 676                        worktree_id: self.id().to_proto(),
 677                        summary: Some(proto::DiagnosticSummary {
 678                            path: worktree_path.to_string_lossy().to_string(),
 679                            language_server_id: server_id.0 as u64,
 680                            error_count: new_summary.error_count as u32,
 681                            warning_count: new_summary.warning_count as u32,
 682                        }),
 683                    })
 684                    .log_err();
 685            }
 686        }
 687
 688        Ok(!old_summary.is_empty() || !new_summary.is_empty())
 689    }
 690
 691    fn set_snapshot(&mut self, new_snapshot: LocalSnapshot, cx: &mut ModelContext<Worktree>) {
 692        let updated_repos =
 693            self.changed_repos(&self.git_repositories, &new_snapshot.git_repositories);
 694        self.snapshot = new_snapshot;
 695
 696        if let Some(share) = self.share.as_mut() {
 697            *share.snapshots_tx.borrow_mut() = self.snapshot.clone();
 698        }
 699
 700        if !updated_repos.is_empty() {
 701            cx.emit(Event::UpdatedGitRepositories(updated_repos));
 702        }
 703    }
 704
 705    fn changed_repos(
 706        &self,
 707        old_repos: &TreeMap<ProjectEntryId, LocalRepositoryEntry>,
 708        new_repos: &TreeMap<ProjectEntryId, LocalRepositoryEntry>,
 709    ) -> HashMap<Arc<Path>, LocalRepositoryEntry> {
 710        let mut diff = HashMap::default();
 711        let mut old_repos = old_repos.iter().peekable();
 712        let mut new_repos = new_repos.iter().peekable();
 713        loop {
 714            match (old_repos.peek(), new_repos.peek()) {
 715                (Some((old_entry_id, old_repo)), Some((new_entry_id, new_repo))) => {
 716                    match Ord::cmp(old_entry_id, new_entry_id) {
 717                        Ordering::Less => {
 718                            if let Some(entry) = self.entry_for_id(**old_entry_id) {
 719                                diff.insert(entry.path.clone(), (*old_repo).clone());
 720                            }
 721                            old_repos.next();
 722                        }
 723                        Ordering::Equal => {
 724                            if old_repo.scan_id != new_repo.scan_id {
 725                                if let Some(entry) = self.entry_for_id(**new_entry_id) {
 726                                    diff.insert(entry.path.clone(), (*new_repo).clone());
 727                                }
 728                            }
 729
 730                            old_repos.next();
 731                            new_repos.next();
 732                        }
 733                        Ordering::Greater => {
 734                            if let Some(entry) = self.entry_for_id(**new_entry_id) {
 735                                diff.insert(entry.path.clone(), (*new_repo).clone());
 736                            }
 737                            new_repos.next();
 738                        }
 739                    }
 740                }
 741                (Some((old_entry_id, old_repo)), None) => {
 742                    if let Some(entry) = self.entry_for_id(**old_entry_id) {
 743                        diff.insert(entry.path.clone(), (*old_repo).clone());
 744                    }
 745                    old_repos.next();
 746                }
 747                (None, Some((new_entry_id, new_repo))) => {
 748                    if let Some(entry) = self.entry_for_id(**new_entry_id) {
 749                        diff.insert(entry.path.clone(), (*new_repo).clone());
 750                    }
 751                    new_repos.next();
 752                }
 753                (None, None) => break,
 754            }
 755        }
 756        diff
 757    }
 758
 759    pub fn scan_complete(&self) -> impl Future<Output = ()> {
 760        let mut is_scanning_rx = self.is_scanning.1.clone();
 761        async move {
 762            let mut is_scanning = is_scanning_rx.borrow().clone();
 763            while is_scanning {
 764                if let Some(value) = is_scanning_rx.recv().await {
 765                    is_scanning = value;
 766                } else {
 767                    break;
 768                }
 769            }
 770        }
 771    }
 772
 773    pub fn snapshot(&self) -> LocalSnapshot {
 774        self.snapshot.clone()
 775    }
 776
 777    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
 778        proto::WorktreeMetadata {
 779            id: self.id().to_proto(),
 780            root_name: self.root_name().to_string(),
 781            visible: self.visible,
 782            abs_path: self.abs_path().as_os_str().to_string_lossy().into(),
 783        }
 784    }
 785
 786    fn load(
 787        &self,
 788        path: &Path,
 789        cx: &mut ModelContext<Worktree>,
 790    ) -> Task<Result<(File, String, Option<String>)>> {
 791        let handle = cx.handle();
 792        let path = Arc::from(path);
 793        let abs_path = self.absolutize(&path);
 794        let fs = self.fs.clone();
 795        let snapshot = self.snapshot();
 796
 797        let mut index_task = None;
 798
 799        if let Some(repo) = snapshot.repo_for(&path) {
 800            let repo_path = repo.work_directory.relativize(self, &path).unwrap();
 801            if let Some(repo) = self.git_repositories.get(&*repo.work_directory) {
 802                let repo = repo.repo_ptr.to_owned();
 803                index_task = Some(
 804                    cx.background()
 805                        .spawn(async move { repo.lock().load_index_text(&repo_path) }),
 806                );
 807            }
 808        }
 809
 810        cx.spawn(|this, mut cx| async move {
 811            let text = fs.load(&abs_path).await?;
 812
 813            let diff_base = if let Some(index_task) = index_task {
 814                index_task.await
 815            } else {
 816                None
 817            };
 818
 819            // Eagerly populate the snapshot with an updated entry for the loaded file
 820            let entry = this
 821                .update(&mut cx, |this, cx| {
 822                    this.as_local().unwrap().refresh_entry(path, None, cx)
 823                })
 824                .await?;
 825
 826            Ok((
 827                File {
 828                    entry_id: entry.id,
 829                    worktree: handle,
 830                    path: entry.path,
 831                    mtime: entry.mtime,
 832                    is_local: true,
 833                    is_deleted: false,
 834                },
 835                text,
 836                diff_base,
 837            ))
 838        })
 839    }
 840
 841    pub fn save_buffer(
 842        &self,
 843        buffer_handle: ModelHandle<Buffer>,
 844        path: Arc<Path>,
 845        has_changed_file: bool,
 846        cx: &mut ModelContext<Worktree>,
 847    ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
 848        let handle = cx.handle();
 849        let buffer = buffer_handle.read(cx);
 850
 851        let rpc = self.client.clone();
 852        let buffer_id = buffer.remote_id();
 853        let project_id = self.share.as_ref().map(|share| share.project_id);
 854
 855        let text = buffer.as_rope().clone();
 856        let fingerprint = text.fingerprint();
 857        let version = buffer.version();
 858        let save = self.write_file(path, text, buffer.line_ending(), cx);
 859
 860        cx.as_mut().spawn(|mut cx| async move {
 861            let entry = save.await?;
 862
 863            if has_changed_file {
 864                let new_file = Arc::new(File {
 865                    entry_id: entry.id,
 866                    worktree: handle,
 867                    path: entry.path,
 868                    mtime: entry.mtime,
 869                    is_local: true,
 870                    is_deleted: false,
 871                });
 872
 873                if let Some(project_id) = project_id {
 874                    rpc.send(proto::UpdateBufferFile {
 875                        project_id,
 876                        buffer_id,
 877                        file: Some(new_file.to_proto()),
 878                    })
 879                    .log_err();
 880                }
 881
 882                buffer_handle.update(&mut cx, |buffer, cx| {
 883                    if has_changed_file {
 884                        buffer.file_updated(new_file, cx).detach();
 885                    }
 886                });
 887            }
 888
 889            if let Some(project_id) = project_id {
 890                rpc.send(proto::BufferSaved {
 891                    project_id,
 892                    buffer_id,
 893                    version: serialize_version(&version),
 894                    mtime: Some(entry.mtime.into()),
 895                    fingerprint: serialize_fingerprint(fingerprint),
 896                })?;
 897            }
 898
 899            buffer_handle.update(&mut cx, |buffer, cx| {
 900                buffer.did_save(version.clone(), fingerprint, entry.mtime, cx);
 901            });
 902
 903            Ok((version, fingerprint, entry.mtime))
 904        })
 905    }
 906
 907    pub fn create_entry(
 908        &self,
 909        path: impl Into<Arc<Path>>,
 910        is_dir: bool,
 911        cx: &mut ModelContext<Worktree>,
 912    ) -> Task<Result<Entry>> {
 913        let path = path.into();
 914        let abs_path = self.absolutize(&path);
 915        let fs = self.fs.clone();
 916        let write = cx.background().spawn(async move {
 917            if is_dir {
 918                fs.create_dir(&abs_path).await
 919            } else {
 920                fs.save(&abs_path, &Default::default(), Default::default())
 921                    .await
 922            }
 923        });
 924
 925        cx.spawn(|this, mut cx| async move {
 926            write.await?;
 927            this.update(&mut cx, |this, cx| {
 928                this.as_local_mut().unwrap().refresh_entry(path, None, cx)
 929            })
 930            .await
 931        })
 932    }
 933
 934    pub fn write_file(
 935        &self,
 936        path: impl Into<Arc<Path>>,
 937        text: Rope,
 938        line_ending: LineEnding,
 939        cx: &mut ModelContext<Worktree>,
 940    ) -> Task<Result<Entry>> {
 941        let path = path.into();
 942        let abs_path = self.absolutize(&path);
 943        let fs = self.fs.clone();
 944        let write = cx
 945            .background()
 946            .spawn(async move { fs.save(&abs_path, &text, line_ending).await });
 947
 948        cx.spawn(|this, mut cx| async move {
 949            write.await?;
 950            this.update(&mut cx, |this, cx| {
 951                this.as_local_mut().unwrap().refresh_entry(path, None, cx)
 952            })
 953            .await
 954        })
 955    }
 956
 957    pub fn delete_entry(
 958        &self,
 959        entry_id: ProjectEntryId,
 960        cx: &mut ModelContext<Worktree>,
 961    ) -> Option<Task<Result<()>>> {
 962        let entry = self.entry_for_id(entry_id)?.clone();
 963        let abs_path = self.abs_path.clone();
 964        let fs = self.fs.clone();
 965
 966        let delete = cx.background().spawn(async move {
 967            let mut abs_path = fs.canonicalize(&abs_path).await?;
 968            if entry.path.file_name().is_some() {
 969                abs_path = abs_path.join(&entry.path);
 970            }
 971            if entry.is_file() {
 972                fs.remove_file(&abs_path, Default::default()).await?;
 973            } else {
 974                fs.remove_dir(
 975                    &abs_path,
 976                    RemoveOptions {
 977                        recursive: true,
 978                        ignore_if_not_exists: false,
 979                    },
 980                )
 981                .await?;
 982            }
 983            anyhow::Ok(abs_path)
 984        });
 985
 986        Some(cx.spawn(|this, mut cx| async move {
 987            let abs_path = delete.await?;
 988            let (tx, mut rx) = barrier::channel();
 989            this.update(&mut cx, |this, _| {
 990                this.as_local_mut()
 991                    .unwrap()
 992                    .path_changes_tx
 993                    .try_send((vec![abs_path], tx))
 994            })?;
 995            rx.recv().await;
 996            Ok(())
 997        }))
 998    }
 999
1000    pub fn rename_entry(
1001        &self,
1002        entry_id: ProjectEntryId,
1003        new_path: impl Into<Arc<Path>>,
1004        cx: &mut ModelContext<Worktree>,
1005    ) -> Option<Task<Result<Entry>>> {
1006        let old_path = self.entry_for_id(entry_id)?.path.clone();
1007        let new_path = new_path.into();
1008        let abs_old_path = self.absolutize(&old_path);
1009        let abs_new_path = self.absolutize(&new_path);
1010        let fs = self.fs.clone();
1011        let rename = cx.background().spawn(async move {
1012            fs.rename(&abs_old_path, &abs_new_path, Default::default())
1013                .await
1014        });
1015
1016        Some(cx.spawn(|this, mut cx| async move {
1017            rename.await?;
1018            this.update(&mut cx, |this, cx| {
1019                this.as_local_mut()
1020                    .unwrap()
1021                    .refresh_entry(new_path.clone(), Some(old_path), cx)
1022            })
1023            .await
1024        }))
1025    }
1026
1027    pub fn copy_entry(
1028        &self,
1029        entry_id: ProjectEntryId,
1030        new_path: impl Into<Arc<Path>>,
1031        cx: &mut ModelContext<Worktree>,
1032    ) -> Option<Task<Result<Entry>>> {
1033        let old_path = self.entry_for_id(entry_id)?.path.clone();
1034        let new_path = new_path.into();
1035        let abs_old_path = self.absolutize(&old_path);
1036        let abs_new_path = self.absolutize(&new_path);
1037        let fs = self.fs.clone();
1038        let copy = cx.background().spawn(async move {
1039            copy_recursive(
1040                fs.as_ref(),
1041                &abs_old_path,
1042                &abs_new_path,
1043                Default::default(),
1044            )
1045            .await
1046        });
1047
1048        Some(cx.spawn(|this, mut cx| async move {
1049            copy.await?;
1050            this.update(&mut cx, |this, cx| {
1051                this.as_local_mut()
1052                    .unwrap()
1053                    .refresh_entry(new_path.clone(), None, cx)
1054            })
1055            .await
1056        }))
1057    }
1058
1059    fn refresh_entry(
1060        &self,
1061        path: Arc<Path>,
1062        old_path: Option<Arc<Path>>,
1063        cx: &mut ModelContext<Worktree>,
1064    ) -> Task<Result<Entry>> {
1065        let fs = self.fs.clone();
1066        let abs_root_path = self.abs_path.clone();
1067        let path_changes_tx = self.path_changes_tx.clone();
1068        cx.spawn_weak(move |this, mut cx| async move {
1069            let abs_path = fs.canonicalize(&abs_root_path).await?;
1070            let mut paths = Vec::with_capacity(2);
1071            paths.push(if path.file_name().is_some() {
1072                abs_path.join(&path)
1073            } else {
1074                abs_path.clone()
1075            });
1076            if let Some(old_path) = old_path {
1077                paths.push(if old_path.file_name().is_some() {
1078                    abs_path.join(&old_path)
1079                } else {
1080                    abs_path.clone()
1081                });
1082            }
1083
1084            let (tx, mut rx) = barrier::channel();
1085            path_changes_tx.try_send((paths, tx))?;
1086            rx.recv().await;
1087            this.upgrade(&cx)
1088                .ok_or_else(|| anyhow!("worktree was dropped"))?
1089                .update(&mut cx, |this, _| {
1090                    this.entry_for_path(path)
1091                        .cloned()
1092                        .ok_or_else(|| anyhow!("failed to read path after update"))
1093                })
1094        })
1095    }
1096
1097    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
1098        let (share_tx, share_rx) = oneshot::channel();
1099
1100        if let Some(share) = self.share.as_mut() {
1101            let _ = share_tx.send(());
1102            *share.resume_updates.borrow_mut() = ();
1103        } else {
1104            let (snapshots_tx, mut snapshots_rx) = watch::channel_with(self.snapshot());
1105            let (resume_updates_tx, mut resume_updates_rx) = watch::channel();
1106            let worktree_id = cx.model_id() as u64;
1107
1108            for (path, summaries) in &self.diagnostic_summaries {
1109                for (&server_id, summary) in summaries {
1110                    if let Err(e) = self.client.send(proto::UpdateDiagnosticSummary {
1111                        project_id,
1112                        worktree_id,
1113                        summary: Some(summary.to_proto(server_id, &path)),
1114                    }) {
1115                        return Task::ready(Err(e));
1116                    }
1117                }
1118            }
1119
1120            let _maintain_remote_snapshot = cx.background().spawn({
1121                let client = self.client.clone();
1122                async move {
1123                    let mut share_tx = Some(share_tx);
1124                    let mut prev_snapshot = LocalSnapshot {
1125                        ignores_by_parent_abs_path: Default::default(),
1126                        removed_entry_ids: Default::default(),
1127                        next_entry_id: Default::default(),
1128                        git_repositories: Default::default(),
1129                        snapshot: Snapshot {
1130                            id: WorktreeId(worktree_id as usize),
1131                            abs_path: Path::new("").into(),
1132                            root_name: Default::default(),
1133                            root_char_bag: Default::default(),
1134                            entries_by_path: Default::default(),
1135                            entries_by_id: Default::default(),
1136                            repository_entries: Default::default(),
1137                            scan_id: 0,
1138                            completed_scan_id: 0,
1139                        },
1140                    };
1141                    while let Some(snapshot) = snapshots_rx.recv().await {
1142                        #[cfg(any(test, feature = "test-support"))]
1143                        const MAX_CHUNK_SIZE: usize = 2;
1144                        #[cfg(not(any(test, feature = "test-support")))]
1145                        const MAX_CHUNK_SIZE: usize = 256;
1146
1147                        let update =
1148                            snapshot.build_update(&prev_snapshot, project_id, worktree_id, true);
1149                        for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
1150                            let _ = resume_updates_rx.try_recv();
1151                            while let Err(error) = client.request(update.clone()).await {
1152                                log::error!("failed to send worktree update: {}", error);
1153                                log::info!("waiting to resume updates");
1154                                if resume_updates_rx.next().await.is_none() {
1155                                    return Ok(());
1156                                }
1157                            }
1158                        }
1159
1160                        if let Some(share_tx) = share_tx.take() {
1161                            let _ = share_tx.send(());
1162                        }
1163
1164                        prev_snapshot = snapshot;
1165                    }
1166
1167                    Ok::<_, anyhow::Error>(())
1168                }
1169                .log_err()
1170            });
1171
1172            self.share = Some(ShareState {
1173                project_id,
1174                snapshots_tx,
1175                resume_updates: resume_updates_tx,
1176                _maintain_remote_snapshot,
1177            });
1178        }
1179
1180        cx.foreground()
1181            .spawn(async move { share_rx.await.map_err(|_| anyhow!("share ended")) })
1182    }
1183
1184    pub fn unshare(&mut self) {
1185        self.share.take();
1186    }
1187
1188    pub fn is_shared(&self) -> bool {
1189        self.share.is_some()
1190    }
1191}
1192
1193impl RemoteWorktree {
1194    fn snapshot(&self) -> Snapshot {
1195        self.snapshot.clone()
1196    }
1197
1198    pub fn disconnected_from_host(&mut self) {
1199        self.updates_tx.take();
1200        self.snapshot_subscriptions.clear();
1201        self.disconnected = true;
1202    }
1203
1204    pub fn save_buffer(
1205        &self,
1206        buffer_handle: ModelHandle<Buffer>,
1207        cx: &mut ModelContext<Worktree>,
1208    ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1209        let buffer = buffer_handle.read(cx);
1210        let buffer_id = buffer.remote_id();
1211        let version = buffer.version();
1212        let rpc = self.client.clone();
1213        let project_id = self.project_id;
1214        cx.as_mut().spawn(|mut cx| async move {
1215            let response = rpc
1216                .request(proto::SaveBuffer {
1217                    project_id,
1218                    buffer_id,
1219                    version: serialize_version(&version),
1220                })
1221                .await?;
1222            let version = deserialize_version(&response.version);
1223            let fingerprint = deserialize_fingerprint(&response.fingerprint)?;
1224            let mtime = response
1225                .mtime
1226                .ok_or_else(|| anyhow!("missing mtime"))?
1227                .into();
1228
1229            buffer_handle.update(&mut cx, |buffer, cx| {
1230                buffer.did_save(version.clone(), fingerprint, mtime, cx);
1231            });
1232
1233            Ok((version, fingerprint, mtime))
1234        })
1235    }
1236
1237    pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1238        if let Some(updates_tx) = &self.updates_tx {
1239            updates_tx
1240                .unbounded_send(update)
1241                .expect("consumer runs to completion");
1242        }
1243    }
1244
1245    fn observed_snapshot(&self, scan_id: usize) -> bool {
1246        self.completed_scan_id >= scan_id
1247    }
1248
1249    fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1250        let (tx, rx) = oneshot::channel();
1251        if self.observed_snapshot(scan_id) {
1252            let _ = tx.send(());
1253        } else if self.disconnected {
1254            drop(tx);
1255        } else {
1256            match self
1257                .snapshot_subscriptions
1258                .binary_search_by_key(&scan_id, |probe| probe.0)
1259            {
1260                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1261            }
1262        }
1263
1264        async move {
1265            rx.await?;
1266            Ok(())
1267        }
1268    }
1269
1270    pub fn update_diagnostic_summary(
1271        &mut self,
1272        path: Arc<Path>,
1273        summary: &proto::DiagnosticSummary,
1274    ) {
1275        let server_id = LanguageServerId(summary.language_server_id as usize);
1276        let summary = DiagnosticSummary {
1277            error_count: summary.error_count as usize,
1278            warning_count: summary.warning_count as usize,
1279        };
1280
1281        if summary.is_empty() {
1282            if let Some(summaries) = self.diagnostic_summaries.get_mut(&path) {
1283                summaries.remove(&server_id);
1284                if summaries.is_empty() {
1285                    self.diagnostic_summaries.remove(&path);
1286                }
1287            }
1288        } else {
1289            self.diagnostic_summaries
1290                .entry(path)
1291                .or_default()
1292                .insert(server_id, summary);
1293        }
1294    }
1295
1296    pub fn insert_entry(
1297        &mut self,
1298        entry: proto::Entry,
1299        scan_id: usize,
1300        cx: &mut ModelContext<Worktree>,
1301    ) -> Task<Result<Entry>> {
1302        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1303        cx.spawn(|this, mut cx| async move {
1304            wait_for_snapshot.await?;
1305            this.update(&mut cx, |worktree, _| {
1306                let worktree = worktree.as_remote_mut().unwrap();
1307                let mut snapshot = worktree.background_snapshot.lock();
1308                let entry = snapshot.insert_entry(entry);
1309                worktree.snapshot = snapshot.clone();
1310                entry
1311            })
1312        })
1313    }
1314
1315    pub(crate) fn delete_entry(
1316        &mut self,
1317        id: ProjectEntryId,
1318        scan_id: usize,
1319        cx: &mut ModelContext<Worktree>,
1320    ) -> Task<Result<()>> {
1321        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1322        cx.spawn(|this, mut cx| async move {
1323            wait_for_snapshot.await?;
1324            this.update(&mut cx, |worktree, _| {
1325                let worktree = worktree.as_remote_mut().unwrap();
1326                let mut snapshot = worktree.background_snapshot.lock();
1327                snapshot.delete_entry(id);
1328                worktree.snapshot = snapshot.clone();
1329            });
1330            Ok(())
1331        })
1332    }
1333}
1334
1335impl Snapshot {
1336    pub fn id(&self) -> WorktreeId {
1337        self.id
1338    }
1339
1340    pub fn abs_path(&self) -> &Arc<Path> {
1341        &self.abs_path
1342    }
1343
1344    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1345        self.entries_by_id.get(&entry_id, &()).is_some()
1346    }
1347
1348    pub(crate) fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1349        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1350        let old_entry = self.entries_by_id.insert_or_replace(
1351            PathEntry {
1352                id: entry.id,
1353                path: entry.path.clone(),
1354                is_ignored: entry.is_ignored,
1355                scan_id: 0,
1356            },
1357            &(),
1358        );
1359        if let Some(old_entry) = old_entry {
1360            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1361        }
1362        self.entries_by_path.insert_or_replace(entry.clone(), &());
1363        Ok(entry)
1364    }
1365
1366    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
1367        let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
1368        self.entries_by_path = {
1369            let mut cursor = self.entries_by_path.cursor();
1370            let mut new_entries_by_path =
1371                cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1372            while let Some(entry) = cursor.item() {
1373                if entry.path.starts_with(&removed_entry.path) {
1374                    self.entries_by_id.remove(&entry.id, &());
1375                    cursor.next(&());
1376                } else {
1377                    break;
1378                }
1379            }
1380            new_entries_by_path.push_tree(cursor.suffix(&()), &());
1381            new_entries_by_path
1382        };
1383
1384        Some(removed_entry.path)
1385    }
1386
1387    pub(crate) fn apply_remote_update(&mut self, mut update: proto::UpdateWorktree) -> Result<()> {
1388        let mut entries_by_path_edits = Vec::new();
1389        let mut entries_by_id_edits = Vec::new();
1390        for entry_id in update.removed_entries {
1391            if let Some(entry) = self.entry_for_id(ProjectEntryId::from_proto(entry_id)) {
1392                entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1393                entries_by_id_edits.push(Edit::Remove(entry.id));
1394            }
1395        }
1396
1397        for entry in update.updated_entries {
1398            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1399            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1400                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1401            }
1402            entries_by_id_edits.push(Edit::Insert(PathEntry {
1403                id: entry.id,
1404                path: entry.path.clone(),
1405                is_ignored: entry.is_ignored,
1406                scan_id: 0,
1407            }));
1408            entries_by_path_edits.push(Edit::Insert(entry));
1409        }
1410
1411        self.entries_by_path.edit(entries_by_path_edits, &());
1412        self.entries_by_id.edit(entries_by_id_edits, &());
1413
1414        update.removed_repositories.sort_unstable();
1415        self.repository_entries.retain(|_, entry| {
1416            if let Ok(_) = update
1417                .removed_repositories
1418                .binary_search(&entry.work_directory.to_proto())
1419            {
1420                false
1421            } else {
1422                true
1423            }
1424        });
1425
1426        for repository in update.updated_repositories {
1427            let repository = RepositoryEntry {
1428                work_directory: ProjectEntryId::from_proto(repository.work_directory_id).into(),
1429                branch: repository.branch.map(Into::into),
1430            };
1431            if let Some(entry) = self.entry_for_id(repository.work_directory_id()) {
1432                self.repository_entries
1433                    .insert(RepositoryWorkDirectory(entry.path.clone()), repository)
1434            } else {
1435                log::error!("no work directory entry for repository {:?}", repository)
1436            }
1437        }
1438
1439        self.scan_id = update.scan_id as usize;
1440        if update.is_last_update {
1441            self.completed_scan_id = update.scan_id as usize;
1442        }
1443
1444        Ok(())
1445    }
1446
1447    pub fn file_count(&self) -> usize {
1448        self.entries_by_path.summary().file_count
1449    }
1450
1451    pub fn visible_file_count(&self) -> usize {
1452        self.entries_by_path.summary().visible_file_count
1453    }
1454
1455    fn traverse_from_offset(
1456        &self,
1457        include_dirs: bool,
1458        include_ignored: bool,
1459        start_offset: usize,
1460    ) -> Traversal {
1461        let mut cursor = self.entries_by_path.cursor();
1462        cursor.seek(
1463            &TraversalTarget::Count {
1464                count: start_offset,
1465                include_dirs,
1466                include_ignored,
1467            },
1468            Bias::Right,
1469            &(),
1470        );
1471        Traversal {
1472            cursor,
1473            include_dirs,
1474            include_ignored,
1475        }
1476    }
1477
1478    fn traverse_from_path(
1479        &self,
1480        include_dirs: bool,
1481        include_ignored: bool,
1482        path: &Path,
1483    ) -> Traversal {
1484        let mut cursor = self.entries_by_path.cursor();
1485        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
1486        Traversal {
1487            cursor,
1488            include_dirs,
1489            include_ignored,
1490        }
1491    }
1492
1493    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
1494        self.traverse_from_offset(false, include_ignored, start)
1495    }
1496
1497    pub fn entries(&self, include_ignored: bool) -> Traversal {
1498        self.traverse_from_offset(true, include_ignored, 0)
1499    }
1500
1501    pub fn repositories(&self) -> impl Iterator<Item = &RepositoryEntry> {
1502        self.repository_entries.values()
1503    }
1504
1505    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
1506        let empty_path = Path::new("");
1507        self.entries_by_path
1508            .cursor::<()>()
1509            .filter(move |entry| entry.path.as_ref() != empty_path)
1510            .map(|entry| &entry.path)
1511    }
1512
1513    fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
1514        let mut cursor = self.entries_by_path.cursor();
1515        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
1516        let traversal = Traversal {
1517            cursor,
1518            include_dirs: true,
1519            include_ignored: true,
1520        };
1521        ChildEntriesIter {
1522            traversal,
1523            parent_path,
1524        }
1525    }
1526
1527    pub fn root_entry(&self) -> Option<&Entry> {
1528        self.entry_for_path("")
1529    }
1530
1531    pub fn root_name(&self) -> &str {
1532        &self.root_name
1533    }
1534
1535    pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
1536        self.repository_entries
1537            .get(&RepositoryWorkDirectory(Path::new("").into()))
1538            .map(|entry| entry.to_owned())
1539    }
1540
1541    pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
1542        self.repository_entries.values()
1543    }
1544
1545    pub fn scan_id(&self) -> usize {
1546        self.scan_id
1547    }
1548
1549    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
1550        let path = path.as_ref();
1551        self.traverse_from_path(true, true, path)
1552            .entry()
1553            .and_then(|entry| {
1554                if entry.path.as_ref() == path {
1555                    Some(entry)
1556                } else {
1557                    None
1558                }
1559            })
1560    }
1561
1562    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
1563        let entry = self.entries_by_id.get(&id, &())?;
1564        self.entry_for_path(&entry.path)
1565    }
1566
1567    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
1568        self.entry_for_path(path.as_ref()).map(|e| e.inode)
1569    }
1570}
1571
1572impl LocalSnapshot {
1573    pub(crate) fn repo_for(&self, path: &Path) -> Option<RepositoryEntry> {
1574        let mut max_len = 0;
1575        let mut current_candidate = None;
1576        for (work_directory, repo) in (&self.repository_entries).iter() {
1577            if repo.contains(self, path) {
1578                if work_directory.0.as_os_str().len() >= max_len {
1579                    current_candidate = Some(repo);
1580                    max_len = work_directory.0.as_os_str().len();
1581                } else {
1582                    break;
1583                }
1584            }
1585        }
1586
1587        current_candidate.map(|entry| entry.to_owned())
1588    }
1589
1590    pub(crate) fn repo_for_metadata(
1591        &self,
1592        path: &Path,
1593    ) -> Option<(ProjectEntryId, Arc<Mutex<dyn GitRepository>>)> {
1594        let (entry_id, local_repo) = self
1595            .git_repositories
1596            .iter()
1597            .find(|(_, repo)| repo.in_dot_git(path))?;
1598        Some((*entry_id, local_repo.repo_ptr.to_owned()))
1599    }
1600
1601    #[cfg(test)]
1602    pub(crate) fn build_initial_update(&self, project_id: u64) -> proto::UpdateWorktree {
1603        let root_name = self.root_name.clone();
1604        proto::UpdateWorktree {
1605            project_id,
1606            worktree_id: self.id().to_proto(),
1607            abs_path: self.abs_path().to_string_lossy().into(),
1608            root_name,
1609            updated_entries: self.entries_by_path.iter().map(Into::into).collect(),
1610            removed_entries: Default::default(),
1611            scan_id: self.scan_id as u64,
1612            is_last_update: true,
1613            updated_repositories: self.repository_entries.values().map(Into::into).collect(),
1614            removed_repositories: Default::default(),
1615        }
1616    }
1617
1618    pub(crate) fn build_update(
1619        &self,
1620        other: &Self,
1621        project_id: u64,
1622        worktree_id: u64,
1623        include_ignored: bool,
1624    ) -> proto::UpdateWorktree {
1625        let mut updated_entries = Vec::new();
1626        let mut removed_entries = Vec::new();
1627        let mut self_entries = self
1628            .entries_by_id
1629            .cursor::<()>()
1630            .filter(|e| include_ignored || !e.is_ignored)
1631            .peekable();
1632        let mut other_entries = other
1633            .entries_by_id
1634            .cursor::<()>()
1635            .filter(|e| include_ignored || !e.is_ignored)
1636            .peekable();
1637        loop {
1638            match (self_entries.peek(), other_entries.peek()) {
1639                (Some(self_entry), Some(other_entry)) => {
1640                    match Ord::cmp(&self_entry.id, &other_entry.id) {
1641                        Ordering::Less => {
1642                            let entry = self.entry_for_id(self_entry.id).unwrap().into();
1643                            updated_entries.push(entry);
1644                            self_entries.next();
1645                        }
1646                        Ordering::Equal => {
1647                            if self_entry.scan_id != other_entry.scan_id {
1648                                let entry = self.entry_for_id(self_entry.id).unwrap().into();
1649                                updated_entries.push(entry);
1650                            }
1651
1652                            self_entries.next();
1653                            other_entries.next();
1654                        }
1655                        Ordering::Greater => {
1656                            removed_entries.push(other_entry.id.to_proto());
1657                            other_entries.next();
1658                        }
1659                    }
1660                }
1661                (Some(self_entry), None) => {
1662                    let entry = self.entry_for_id(self_entry.id).unwrap().into();
1663                    updated_entries.push(entry);
1664                    self_entries.next();
1665                }
1666                (None, Some(other_entry)) => {
1667                    removed_entries.push(other_entry.id.to_proto());
1668                    other_entries.next();
1669                }
1670                (None, None) => break,
1671            }
1672        }
1673
1674        let mut updated_repositories: Vec<proto::RepositoryEntry> = Vec::new();
1675        let mut removed_repositories = Vec::new();
1676        let mut self_repos = self.snapshot.repository_entries.values().peekable();
1677        let mut other_repos = other.snapshot.repository_entries.values().peekable();
1678        loop {
1679            match (self_repos.peek(), other_repos.peek()) {
1680                (Some(self_repo), Some(other_repo)) => {
1681                    match Ord::cmp(&self_repo.work_directory, &other_repo.work_directory) {
1682                        Ordering::Less => {
1683                            updated_repositories.push((*self_repo).into());
1684                            self_repos.next();
1685                        }
1686                        Ordering::Equal => {
1687                            if self_repo != other_repo {
1688                                updated_repositories.push((*self_repo).into());
1689                            }
1690
1691                            self_repos.next();
1692                            other_repos.next();
1693                        }
1694                        Ordering::Greater => {
1695                            removed_repositories.push(other_repo.work_directory.to_proto());
1696                            other_repos.next();
1697                        }
1698                    }
1699                }
1700                (Some(self_repo), None) => {
1701                    updated_repositories.push((*self_repo).into());
1702                    self_repos.next();
1703                }
1704                (None, Some(other_repo)) => {
1705                    removed_repositories.push(other_repo.work_directory.to_proto());
1706                    other_repos.next();
1707                }
1708                (None, None) => break,
1709            }
1710        }
1711
1712        proto::UpdateWorktree {
1713            project_id,
1714            worktree_id,
1715            abs_path: self.abs_path().to_string_lossy().into(),
1716            root_name: self.root_name().to_string(),
1717            updated_entries,
1718            removed_entries,
1719            scan_id: self.scan_id as u64,
1720            is_last_update: self.completed_scan_id == self.scan_id,
1721            updated_repositories,
1722            removed_repositories,
1723        }
1724    }
1725
1726    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
1727        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
1728            let abs_path = self.abs_path.join(&entry.path);
1729            match smol::block_on(build_gitignore(&abs_path, fs)) {
1730                Ok(ignore) => {
1731                    self.ignores_by_parent_abs_path.insert(
1732                        abs_path.parent().unwrap().into(),
1733                        (Arc::new(ignore), self.scan_id),
1734                    );
1735                }
1736                Err(error) => {
1737                    log::error!(
1738                        "error loading .gitignore file {:?} - {:?}",
1739                        &entry.path,
1740                        error
1741                    );
1742                }
1743            }
1744        }
1745
1746        self.reuse_entry_id(&mut entry);
1747
1748        if entry.kind == EntryKind::PendingDir {
1749            if let Some(existing_entry) =
1750                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
1751            {
1752                entry.kind = existing_entry.kind;
1753            }
1754        }
1755
1756        let scan_id = self.scan_id;
1757        let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
1758        if let Some(removed) = removed {
1759            if removed.id != entry.id {
1760                self.entries_by_id.remove(&removed.id, &());
1761            }
1762        }
1763        self.entries_by_id.insert_or_replace(
1764            PathEntry {
1765                id: entry.id,
1766                path: entry.path.clone(),
1767                is_ignored: entry.is_ignored,
1768                scan_id,
1769            },
1770            &(),
1771        );
1772
1773        entry
1774    }
1775
1776    fn populate_dir(
1777        &mut self,
1778        parent_path: Arc<Path>,
1779        entries: impl IntoIterator<Item = Entry>,
1780        ignore: Option<Arc<Gitignore>>,
1781        fs: &dyn Fs,
1782    ) {
1783        let mut parent_entry = if let Some(parent_entry) =
1784            self.entries_by_path.get(&PathKey(parent_path.clone()), &())
1785        {
1786            parent_entry.clone()
1787        } else {
1788            log::warn!(
1789                "populating a directory {:?} that has been removed",
1790                parent_path
1791            );
1792            return;
1793        };
1794
1795        match parent_entry.kind {
1796            EntryKind::PendingDir => {
1797                parent_entry.kind = EntryKind::Dir;
1798            }
1799            EntryKind::Dir => {}
1800            _ => return,
1801        }
1802
1803        if let Some(ignore) = ignore {
1804            self.ignores_by_parent_abs_path.insert(
1805                self.abs_path.join(&parent_path).into(),
1806                (ignore, self.scan_id),
1807            );
1808        }
1809
1810        if parent_path.file_name() == Some(&DOT_GIT) {
1811            let abs_path = self.abs_path.join(&parent_path);
1812            let work_dir: Arc<Path> = parent_path.parent().unwrap().into();
1813
1814            if let Some(work_dir_id) = self.entry_for_path(work_dir.clone()).map(|entry| entry.id) {
1815                if self.git_repositories.get(&work_dir_id).is_none() {
1816                    if let Some(repo) = fs.open_repo(abs_path.as_path()) {
1817                        let work_directory = RepositoryWorkDirectory(work_dir.clone());
1818
1819                        let repo_lock = repo.lock();
1820                        let scan_id = self.scan_id;
1821                        self.repository_entries.insert(
1822                            work_directory,
1823                            RepositoryEntry {
1824                                work_directory: work_dir_id.into(),
1825                                branch: repo_lock.branch_name().map(Into::into),
1826                            },
1827                        );
1828                        drop(repo_lock);
1829
1830                        self.git_repositories.insert(
1831                            work_dir_id,
1832                            LocalRepositoryEntry {
1833                                scan_id,
1834                                repo_ptr: repo,
1835                                git_dir_path: parent_path.clone(),
1836                            },
1837                        )
1838                    }
1839                }
1840            }
1841        }
1842
1843        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
1844        let mut entries_by_id_edits = Vec::new();
1845
1846        for mut entry in entries {
1847            self.reuse_entry_id(&mut entry);
1848            entries_by_id_edits.push(Edit::Insert(PathEntry {
1849                id: entry.id,
1850                path: entry.path.clone(),
1851                is_ignored: entry.is_ignored,
1852                scan_id: self.scan_id,
1853            }));
1854            entries_by_path_edits.push(Edit::Insert(entry));
1855        }
1856
1857        self.entries_by_path.edit(entries_by_path_edits, &());
1858        self.entries_by_id.edit(entries_by_id_edits, &());
1859    }
1860
1861    fn reuse_entry_id(&mut self, entry: &mut Entry) {
1862        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
1863            entry.id = removed_entry_id;
1864        } else if let Some(existing_entry) = self.entry_for_path(&entry.path) {
1865            entry.id = existing_entry.id;
1866        }
1867    }
1868
1869    fn remove_path(&mut self, path: &Path) {
1870        let mut new_entries;
1871        let removed_entries;
1872        {
1873            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1874            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
1875            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
1876            new_entries.push_tree(cursor.suffix(&()), &());
1877        }
1878        self.entries_by_path = new_entries;
1879
1880        let mut entries_by_id_edits = Vec::new();
1881        for entry in removed_entries.cursor::<()>() {
1882            let removed_entry_id = self
1883                .removed_entry_ids
1884                .entry(entry.inode)
1885                .or_insert(entry.id);
1886            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
1887            entries_by_id_edits.push(Edit::Remove(entry.id));
1888        }
1889        self.entries_by_id.edit(entries_by_id_edits, &());
1890
1891        if path.file_name() == Some(&GITIGNORE) {
1892            let abs_parent_path = self.abs_path.join(path.parent().unwrap());
1893            if let Some((_, scan_id)) = self
1894                .ignores_by_parent_abs_path
1895                .get_mut(abs_parent_path.as_path())
1896            {
1897                *scan_id = self.snapshot.scan_id;
1898            }
1899        }
1900    }
1901
1902    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
1903        let mut inodes = TreeSet::default();
1904        for ancestor in path.ancestors().skip(1) {
1905            if let Some(entry) = self.entry_for_path(ancestor) {
1906                inodes.insert(entry.inode);
1907            }
1908        }
1909        inodes
1910    }
1911
1912    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
1913        let mut new_ignores = Vec::new();
1914        for ancestor in abs_path.ancestors().skip(1) {
1915            if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
1916                new_ignores.push((ancestor, Some(ignore.clone())));
1917            } else {
1918                new_ignores.push((ancestor, None));
1919            }
1920        }
1921
1922        let mut ignore_stack = IgnoreStack::none();
1923        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
1924            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
1925                ignore_stack = IgnoreStack::all();
1926                break;
1927            } else if let Some(ignore) = ignore {
1928                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
1929            }
1930        }
1931
1932        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
1933            ignore_stack = IgnoreStack::all();
1934        }
1935
1936        ignore_stack
1937    }
1938}
1939
1940async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
1941    let contents = fs.load(abs_path).await?;
1942    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
1943    let mut builder = GitignoreBuilder::new(parent);
1944    for line in contents.lines() {
1945        builder.add_line(Some(abs_path.into()), line)?;
1946    }
1947    Ok(builder.build()?)
1948}
1949
1950impl WorktreeId {
1951    pub fn from_usize(handle_id: usize) -> Self {
1952        Self(handle_id)
1953    }
1954
1955    pub(crate) fn from_proto(id: u64) -> Self {
1956        Self(id as usize)
1957    }
1958
1959    pub fn to_proto(&self) -> u64 {
1960        self.0 as u64
1961    }
1962
1963    pub fn to_usize(&self) -> usize {
1964        self.0
1965    }
1966}
1967
1968impl fmt::Display for WorktreeId {
1969    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1970        self.0.fmt(f)
1971    }
1972}
1973
1974impl Deref for Worktree {
1975    type Target = Snapshot;
1976
1977    fn deref(&self) -> &Self::Target {
1978        match self {
1979            Worktree::Local(worktree) => &worktree.snapshot,
1980            Worktree::Remote(worktree) => &worktree.snapshot,
1981        }
1982    }
1983}
1984
1985impl Deref for LocalWorktree {
1986    type Target = LocalSnapshot;
1987
1988    fn deref(&self) -> &Self::Target {
1989        &self.snapshot
1990    }
1991}
1992
1993impl Deref for RemoteWorktree {
1994    type Target = Snapshot;
1995
1996    fn deref(&self) -> &Self::Target {
1997        &self.snapshot
1998    }
1999}
2000
2001impl fmt::Debug for LocalWorktree {
2002    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2003        self.snapshot.fmt(f)
2004    }
2005}
2006
2007impl fmt::Debug for Snapshot {
2008    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2009        struct EntriesById<'a>(&'a SumTree<PathEntry>);
2010        struct EntriesByPath<'a>(&'a SumTree<Entry>);
2011
2012        impl<'a> fmt::Debug for EntriesByPath<'a> {
2013            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2014                f.debug_map()
2015                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2016                    .finish()
2017            }
2018        }
2019
2020        impl<'a> fmt::Debug for EntriesById<'a> {
2021            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2022                f.debug_list().entries(self.0.iter()).finish()
2023            }
2024        }
2025
2026        f.debug_struct("Snapshot")
2027            .field("id", &self.id)
2028            .field("root_name", &self.root_name)
2029            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2030            .field("entries_by_id", &EntriesById(&self.entries_by_id))
2031            .finish()
2032    }
2033}
2034
2035#[derive(Clone, PartialEq)]
2036pub struct File {
2037    pub worktree: ModelHandle<Worktree>,
2038    pub path: Arc<Path>,
2039    pub mtime: SystemTime,
2040    pub(crate) entry_id: ProjectEntryId,
2041    pub(crate) is_local: bool,
2042    pub(crate) is_deleted: bool,
2043}
2044
2045impl language::File for File {
2046    fn as_local(&self) -> Option<&dyn language::LocalFile> {
2047        if self.is_local {
2048            Some(self)
2049        } else {
2050            None
2051        }
2052    }
2053
2054    fn mtime(&self) -> SystemTime {
2055        self.mtime
2056    }
2057
2058    fn path(&self) -> &Arc<Path> {
2059        &self.path
2060    }
2061
2062    fn full_path(&self, cx: &AppContext) -> PathBuf {
2063        let mut full_path = PathBuf::new();
2064        let worktree = self.worktree.read(cx);
2065
2066        if worktree.is_visible() {
2067            full_path.push(worktree.root_name());
2068        } else {
2069            let path = worktree.abs_path();
2070
2071            if worktree.is_local() && path.starts_with(HOME.as_path()) {
2072                full_path.push("~");
2073                full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2074            } else {
2075                full_path.push(path)
2076            }
2077        }
2078
2079        if self.path.components().next().is_some() {
2080            full_path.push(&self.path);
2081        }
2082
2083        full_path
2084    }
2085
2086    /// Returns the last component of this handle's absolute path. If this handle refers to the root
2087    /// of its worktree, then this method will return the name of the worktree itself.
2088    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2089        self.path
2090            .file_name()
2091            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2092    }
2093
2094    fn is_deleted(&self) -> bool {
2095        self.is_deleted
2096    }
2097
2098    fn as_any(&self) -> &dyn Any {
2099        self
2100    }
2101
2102    fn to_proto(&self) -> rpc::proto::File {
2103        rpc::proto::File {
2104            worktree_id: self.worktree.id() as u64,
2105            entry_id: self.entry_id.to_proto(),
2106            path: self.path.to_string_lossy().into(),
2107            mtime: Some(self.mtime.into()),
2108            is_deleted: self.is_deleted,
2109        }
2110    }
2111}
2112
2113impl language::LocalFile for File {
2114    fn abs_path(&self, cx: &AppContext) -> PathBuf {
2115        self.worktree
2116            .read(cx)
2117            .as_local()
2118            .unwrap()
2119            .abs_path
2120            .join(&self.path)
2121    }
2122
2123    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2124        let worktree = self.worktree.read(cx).as_local().unwrap();
2125        let abs_path = worktree.absolutize(&self.path);
2126        let fs = worktree.fs.clone();
2127        cx.background()
2128            .spawn(async move { fs.load(&abs_path).await })
2129    }
2130
2131    fn buffer_reloaded(
2132        &self,
2133        buffer_id: u64,
2134        version: &clock::Global,
2135        fingerprint: RopeFingerprint,
2136        line_ending: LineEnding,
2137        mtime: SystemTime,
2138        cx: &mut AppContext,
2139    ) {
2140        let worktree = self.worktree.read(cx).as_local().unwrap();
2141        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2142            worktree
2143                .client
2144                .send(proto::BufferReloaded {
2145                    project_id,
2146                    buffer_id,
2147                    version: serialize_version(version),
2148                    mtime: Some(mtime.into()),
2149                    fingerprint: serialize_fingerprint(fingerprint),
2150                    line_ending: serialize_line_ending(line_ending) as i32,
2151                })
2152                .log_err();
2153        }
2154    }
2155}
2156
2157impl File {
2158    pub fn from_proto(
2159        proto: rpc::proto::File,
2160        worktree: ModelHandle<Worktree>,
2161        cx: &AppContext,
2162    ) -> Result<Self> {
2163        let worktree_id = worktree
2164            .read(cx)
2165            .as_remote()
2166            .ok_or_else(|| anyhow!("not remote"))?
2167            .id();
2168
2169        if worktree_id.to_proto() != proto.worktree_id {
2170            return Err(anyhow!("worktree id does not match file"));
2171        }
2172
2173        Ok(Self {
2174            worktree,
2175            path: Path::new(&proto.path).into(),
2176            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
2177            entry_id: ProjectEntryId::from_proto(proto.entry_id),
2178            is_local: false,
2179            is_deleted: proto.is_deleted,
2180        })
2181    }
2182
2183    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
2184        file.and_then(|f| f.as_any().downcast_ref())
2185    }
2186
2187    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
2188        self.worktree.read(cx).id()
2189    }
2190
2191    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
2192        if self.is_deleted {
2193            None
2194        } else {
2195            Some(self.entry_id)
2196        }
2197    }
2198}
2199
2200#[derive(Clone, Debug, PartialEq, Eq)]
2201pub struct Entry {
2202    pub id: ProjectEntryId,
2203    pub kind: EntryKind,
2204    pub path: Arc<Path>,
2205    pub inode: u64,
2206    pub mtime: SystemTime,
2207    pub is_symlink: bool,
2208    pub is_ignored: bool,
2209}
2210
2211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2212pub enum EntryKind {
2213    PendingDir,
2214    Dir,
2215    File(CharBag),
2216}
2217
2218#[derive(Clone, Copy, Debug)]
2219pub enum PathChange {
2220    Added,
2221    Removed,
2222    Updated,
2223    AddedOrUpdated,
2224}
2225
2226impl Entry {
2227    fn new(
2228        path: Arc<Path>,
2229        metadata: &fs::Metadata,
2230        next_entry_id: &AtomicUsize,
2231        root_char_bag: CharBag,
2232    ) -> Self {
2233        Self {
2234            id: ProjectEntryId::new(next_entry_id),
2235            kind: if metadata.is_dir {
2236                EntryKind::PendingDir
2237            } else {
2238                EntryKind::File(char_bag_for_path(root_char_bag, &path))
2239            },
2240            path,
2241            inode: metadata.inode,
2242            mtime: metadata.mtime,
2243            is_symlink: metadata.is_symlink,
2244            is_ignored: false,
2245        }
2246    }
2247
2248    pub fn is_dir(&self) -> bool {
2249        matches!(self.kind, EntryKind::Dir | EntryKind::PendingDir)
2250    }
2251
2252    pub fn is_file(&self) -> bool {
2253        matches!(self.kind, EntryKind::File(_))
2254    }
2255}
2256
2257impl sum_tree::Item for Entry {
2258    type Summary = EntrySummary;
2259
2260    fn summary(&self) -> Self::Summary {
2261        let visible_count = if self.is_ignored { 0 } else { 1 };
2262        let file_count;
2263        let visible_file_count;
2264        if self.is_file() {
2265            file_count = 1;
2266            visible_file_count = visible_count;
2267        } else {
2268            file_count = 0;
2269            visible_file_count = 0;
2270        }
2271
2272        EntrySummary {
2273            max_path: self.path.clone(),
2274            count: 1,
2275            visible_count,
2276            file_count,
2277            visible_file_count,
2278        }
2279    }
2280}
2281
2282impl sum_tree::KeyedItem for Entry {
2283    type Key = PathKey;
2284
2285    fn key(&self) -> Self::Key {
2286        PathKey(self.path.clone())
2287    }
2288}
2289
2290#[derive(Clone, Debug)]
2291pub struct EntrySummary {
2292    max_path: Arc<Path>,
2293    count: usize,
2294    visible_count: usize,
2295    file_count: usize,
2296    visible_file_count: usize,
2297}
2298
2299impl Default for EntrySummary {
2300    fn default() -> Self {
2301        Self {
2302            max_path: Arc::from(Path::new("")),
2303            count: 0,
2304            visible_count: 0,
2305            file_count: 0,
2306            visible_file_count: 0,
2307        }
2308    }
2309}
2310
2311impl sum_tree::Summary for EntrySummary {
2312    type Context = ();
2313
2314    fn add_summary(&mut self, rhs: &Self, _: &()) {
2315        self.max_path = rhs.max_path.clone();
2316        self.count += rhs.count;
2317        self.visible_count += rhs.visible_count;
2318        self.file_count += rhs.file_count;
2319        self.visible_file_count += rhs.visible_file_count;
2320    }
2321}
2322
2323#[derive(Clone, Debug)]
2324struct PathEntry {
2325    id: ProjectEntryId,
2326    path: Arc<Path>,
2327    is_ignored: bool,
2328    scan_id: usize,
2329}
2330
2331impl sum_tree::Item for PathEntry {
2332    type Summary = PathEntrySummary;
2333
2334    fn summary(&self) -> Self::Summary {
2335        PathEntrySummary { max_id: self.id }
2336    }
2337}
2338
2339impl sum_tree::KeyedItem for PathEntry {
2340    type Key = ProjectEntryId;
2341
2342    fn key(&self) -> Self::Key {
2343        self.id
2344    }
2345}
2346
2347#[derive(Clone, Debug, Default)]
2348struct PathEntrySummary {
2349    max_id: ProjectEntryId,
2350}
2351
2352impl sum_tree::Summary for PathEntrySummary {
2353    type Context = ();
2354
2355    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
2356        self.max_id = summary.max_id;
2357    }
2358}
2359
2360impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
2361    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
2362        *self = summary.max_id;
2363    }
2364}
2365
2366#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
2367pub struct PathKey(Arc<Path>);
2368
2369impl Default for PathKey {
2370    fn default() -> Self {
2371        Self(Path::new("").into())
2372    }
2373}
2374
2375impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
2376    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
2377        self.0 = summary.max_path.clone();
2378    }
2379}
2380
2381struct BackgroundScanner {
2382    snapshot: Mutex<LocalSnapshot>,
2383    fs: Arc<dyn Fs>,
2384    status_updates_tx: UnboundedSender<ScanState>,
2385    executor: Arc<executor::Background>,
2386    refresh_requests_rx: channel::Receiver<(Vec<PathBuf>, barrier::Sender)>,
2387    prev_state: Mutex<(Snapshot, Vec<Arc<Path>>)>,
2388    finished_initial_scan: bool,
2389}
2390
2391impl BackgroundScanner {
2392    fn new(
2393        snapshot: LocalSnapshot,
2394        fs: Arc<dyn Fs>,
2395        status_updates_tx: UnboundedSender<ScanState>,
2396        executor: Arc<executor::Background>,
2397        refresh_requests_rx: channel::Receiver<(Vec<PathBuf>, barrier::Sender)>,
2398    ) -> Self {
2399        Self {
2400            fs,
2401            status_updates_tx,
2402            executor,
2403            refresh_requests_rx,
2404            prev_state: Mutex::new((snapshot.snapshot.clone(), Vec::new())),
2405            snapshot: Mutex::new(snapshot),
2406            finished_initial_scan: false,
2407        }
2408    }
2409
2410    async fn run(
2411        &mut self,
2412        mut events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>,
2413    ) {
2414        use futures::FutureExt as _;
2415
2416        let (root_abs_path, root_inode) = {
2417            let snapshot = self.snapshot.lock();
2418            (
2419                snapshot.abs_path.clone(),
2420                snapshot.root_entry().map(|e| e.inode),
2421            )
2422        };
2423
2424        // Populate ignores above the root.
2425        let ignore_stack;
2426        for ancestor in root_abs_path.ancestors().skip(1) {
2427            if let Ok(ignore) = build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
2428            {
2429                self.snapshot
2430                    .lock()
2431                    .ignores_by_parent_abs_path
2432                    .insert(ancestor.into(), (ignore.into(), 0));
2433            }
2434        }
2435        {
2436            let mut snapshot = self.snapshot.lock();
2437            snapshot.scan_id += 1;
2438            ignore_stack = snapshot.ignore_stack_for_abs_path(&root_abs_path, true);
2439            if ignore_stack.is_all() {
2440                if let Some(mut root_entry) = snapshot.root_entry().cloned() {
2441                    root_entry.is_ignored = true;
2442                    snapshot.insert_entry(root_entry, self.fs.as_ref());
2443                }
2444            }
2445        };
2446
2447        // Perform an initial scan of the directory.
2448        let (scan_job_tx, scan_job_rx) = channel::unbounded();
2449        smol::block_on(scan_job_tx.send(ScanJob {
2450            abs_path: root_abs_path,
2451            path: Arc::from(Path::new("")),
2452            ignore_stack,
2453            ancestor_inodes: TreeSet::from_ordered_entries(root_inode),
2454            scan_queue: scan_job_tx.clone(),
2455        }))
2456        .unwrap();
2457        drop(scan_job_tx);
2458        self.scan_dirs(true, scan_job_rx).await;
2459        {
2460            let mut snapshot = self.snapshot.lock();
2461            snapshot.completed_scan_id = snapshot.scan_id;
2462        }
2463        self.send_status_update(false, None);
2464
2465        // Process any any FS events that occurred while performing the initial scan.
2466        // For these events, update events cannot be as precise, because we didn't
2467        // have the previous state loaded yet.
2468        if let Poll::Ready(Some(events)) = futures::poll!(events_rx.next()) {
2469            let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
2470            while let Poll::Ready(Some(more_events)) = futures::poll!(events_rx.next()) {
2471                paths.extend(more_events.into_iter().map(|e| e.path));
2472            }
2473            self.process_events(paths).await;
2474        }
2475
2476        self.finished_initial_scan = true;
2477
2478        // Continue processing events until the worktree is dropped.
2479        loop {
2480            select_biased! {
2481                // Process any path refresh requests from the worktree. Prioritize
2482                // these before handling changes reported by the filesystem.
2483                request = self.refresh_requests_rx.recv().fuse() => {
2484                    let Ok((paths, barrier)) = request else { break };
2485                    if !self.process_refresh_request(paths, barrier).await {
2486                        return;
2487                    }
2488                }
2489
2490                events = events_rx.next().fuse() => {
2491                    let Some(events) = events else { break };
2492                    let mut paths = events.into_iter().map(|e| e.path).collect::<Vec<_>>();
2493                    while let Poll::Ready(Some(more_events)) = futures::poll!(events_rx.next()) {
2494                        paths.extend(more_events.into_iter().map(|e| e.path));
2495                    }
2496                    self.process_events(paths).await;
2497                }
2498            }
2499        }
2500    }
2501
2502    async fn process_refresh_request(&self, paths: Vec<PathBuf>, barrier: barrier::Sender) -> bool {
2503        self.reload_entries_for_paths(paths, None).await;
2504        self.send_status_update(false, Some(barrier))
2505    }
2506
2507    async fn process_events(&mut self, paths: Vec<PathBuf>) {
2508        let (scan_job_tx, scan_job_rx) = channel::unbounded();
2509        if let Some(mut paths) = self
2510            .reload_entries_for_paths(paths, Some(scan_job_tx.clone()))
2511            .await
2512        {
2513            paths.sort_unstable();
2514            util::extend_sorted(&mut self.prev_state.lock().1, paths, usize::MAX, Ord::cmp);
2515        }
2516        drop(scan_job_tx);
2517        self.scan_dirs(false, scan_job_rx).await;
2518
2519        self.update_ignore_statuses().await;
2520
2521        let mut snapshot = self.snapshot.lock();
2522
2523        let mut git_repositories = mem::take(&mut snapshot.git_repositories);
2524        git_repositories.retain(|work_directory_id, _| {
2525            snapshot
2526                .entry_for_id(*work_directory_id)
2527                .map_or(false, |entry| {
2528                    snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2529                })
2530        });
2531        snapshot.git_repositories = git_repositories;
2532
2533        let mut git_repository_entries = mem::take(&mut snapshot.snapshot.repository_entries);
2534        git_repository_entries.retain(|_, entry| {
2535            snapshot
2536                .git_repositories
2537                .get(&entry.work_directory.0)
2538                .is_some()
2539        });
2540        snapshot.snapshot.repository_entries = git_repository_entries;
2541
2542        snapshot.removed_entry_ids.clear();
2543        snapshot.completed_scan_id = snapshot.scan_id;
2544
2545        drop(snapshot);
2546
2547        self.send_status_update(false, None);
2548    }
2549
2550    async fn scan_dirs(
2551        &self,
2552        enable_progress_updates: bool,
2553        scan_jobs_rx: channel::Receiver<ScanJob>,
2554    ) {
2555        use futures::FutureExt as _;
2556
2557        if self
2558            .status_updates_tx
2559            .unbounded_send(ScanState::Started)
2560            .is_err()
2561        {
2562            return;
2563        }
2564
2565        let progress_update_count = AtomicUsize::new(0);
2566        self.executor
2567            .scoped(|scope| {
2568                for _ in 0..self.executor.num_cpus() {
2569                    scope.spawn(async {
2570                        let mut last_progress_update_count = 0;
2571                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
2572                        futures::pin_mut!(progress_update_timer);
2573
2574                        loop {
2575                            select_biased! {
2576                                // Process any path refresh requests before moving on to process
2577                                // the scan queue, so that user operations are prioritized.
2578                                request = self.refresh_requests_rx.recv().fuse() => {
2579                                    let Ok((paths, barrier)) = request else { break };
2580                                    if !self.process_refresh_request(paths, barrier).await {
2581                                        return;
2582                                    }
2583                                }
2584
2585                                // Send periodic progress updates to the worktree. Use an atomic counter
2586                                // to ensure that only one of the workers sends a progress update after
2587                                // the update interval elapses.
2588                                _ = progress_update_timer => {
2589                                    match progress_update_count.compare_exchange(
2590                                        last_progress_update_count,
2591                                        last_progress_update_count + 1,
2592                                        SeqCst,
2593                                        SeqCst
2594                                    ) {
2595                                        Ok(_) => {
2596                                            last_progress_update_count += 1;
2597                                            self.send_status_update(true, None);
2598                                        }
2599                                        Err(count) => {
2600                                            last_progress_update_count = count;
2601                                        }
2602                                    }
2603                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
2604                                }
2605
2606                                // Recursively load directories from the file system.
2607                                job = scan_jobs_rx.recv().fuse() => {
2608                                    let Ok(job) = job else { break };
2609                                    if let Err(err) = self.scan_dir(&job).await {
2610                                        if job.path.as_ref() != Path::new("") {
2611                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
2612                                        }
2613                                    }
2614                                }
2615                            }
2616                        }
2617                    })
2618                }
2619            })
2620            .await;
2621    }
2622
2623    fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
2624        let mut prev_state = self.prev_state.lock();
2625        let snapshot = self.snapshot.lock().clone();
2626        let mut old_snapshot = snapshot.snapshot.clone();
2627        mem::swap(&mut old_snapshot, &mut prev_state.0);
2628        let changed_paths = mem::take(&mut prev_state.1);
2629        let changes = self.build_change_set(&old_snapshot, &snapshot.snapshot, changed_paths);
2630        self.status_updates_tx
2631            .unbounded_send(ScanState::Updated {
2632                snapshot,
2633                changes,
2634                scanning,
2635                barrier,
2636            })
2637            .is_ok()
2638    }
2639
2640    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
2641        let mut new_entries: Vec<Entry> = Vec::new();
2642        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
2643        let mut ignore_stack = job.ignore_stack.clone();
2644        let mut new_ignore = None;
2645        let (root_abs_path, root_char_bag, next_entry_id) = {
2646            let snapshot = self.snapshot.lock();
2647            (
2648                snapshot.abs_path().clone(),
2649                snapshot.root_char_bag,
2650                snapshot.next_entry_id.clone(),
2651            )
2652        };
2653        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
2654        while let Some(child_abs_path) = child_paths.next().await {
2655            let child_abs_path: Arc<Path> = match child_abs_path {
2656                Ok(child_abs_path) => child_abs_path.into(),
2657                Err(error) => {
2658                    log::error!("error processing entry {:?}", error);
2659                    continue;
2660                }
2661            };
2662
2663            let child_name = child_abs_path.file_name().unwrap();
2664            let child_path: Arc<Path> = job.path.join(child_name).into();
2665            let child_metadata = match self.fs.metadata(&child_abs_path).await {
2666                Ok(Some(metadata)) => metadata,
2667                Ok(None) => continue,
2668                Err(err) => {
2669                    log::error!("error processing {:?}: {:?}", child_abs_path, err);
2670                    continue;
2671                }
2672            };
2673
2674            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
2675            if child_name == *GITIGNORE {
2676                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
2677                    Ok(ignore) => {
2678                        let ignore = Arc::new(ignore);
2679                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2680                        new_ignore = Some(ignore);
2681                    }
2682                    Err(error) => {
2683                        log::error!(
2684                            "error loading .gitignore file {:?} - {:?}",
2685                            child_name,
2686                            error
2687                        );
2688                    }
2689                }
2690
2691                // Update ignore status of any child entries we've already processed to reflect the
2692                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
2693                // there should rarely be too numerous. Update the ignore stack associated with any
2694                // new jobs as well.
2695                let mut new_jobs = new_jobs.iter_mut();
2696                for entry in &mut new_entries {
2697                    let entry_abs_path = root_abs_path.join(&entry.path);
2698                    entry.is_ignored =
2699                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
2700
2701                    if entry.is_dir() {
2702                        if let Some(job) = new_jobs.next().expect("Missing scan job for entry") {
2703                            job.ignore_stack = if entry.is_ignored {
2704                                IgnoreStack::all()
2705                            } else {
2706                                ignore_stack.clone()
2707                            };
2708                        }
2709                    }
2710                }
2711            }
2712
2713            let mut child_entry = Entry::new(
2714                child_path.clone(),
2715                &child_metadata,
2716                &next_entry_id,
2717                root_char_bag,
2718            );
2719
2720            if child_entry.is_dir() {
2721                let is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
2722                child_entry.is_ignored = is_ignored;
2723
2724                // Avoid recursing until crash in the case of a recursive symlink
2725                if !job.ancestor_inodes.contains(&child_entry.inode) {
2726                    let mut ancestor_inodes = job.ancestor_inodes.clone();
2727                    ancestor_inodes.insert(child_entry.inode);
2728
2729                    new_jobs.push(Some(ScanJob {
2730                        abs_path: child_abs_path,
2731                        path: child_path,
2732                        ignore_stack: if is_ignored {
2733                            IgnoreStack::all()
2734                        } else {
2735                            ignore_stack.clone()
2736                        },
2737                        ancestor_inodes,
2738                        scan_queue: job.scan_queue.clone(),
2739                    }));
2740                } else {
2741                    new_jobs.push(None);
2742                }
2743            } else {
2744                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
2745            }
2746
2747            new_entries.push(child_entry);
2748        }
2749
2750        self.snapshot.lock().populate_dir(
2751            job.path.clone(),
2752            new_entries,
2753            new_ignore,
2754            self.fs.as_ref(),
2755        );
2756
2757        for new_job in new_jobs {
2758            if let Some(new_job) = new_job {
2759                job.scan_queue.send(new_job).await.unwrap();
2760            }
2761        }
2762
2763        Ok(())
2764    }
2765
2766    async fn reload_entries_for_paths(
2767        &self,
2768        mut abs_paths: Vec<PathBuf>,
2769        scan_queue_tx: Option<Sender<ScanJob>>,
2770    ) -> Option<Vec<Arc<Path>>> {
2771        let doing_recursive_update = scan_queue_tx.is_some();
2772
2773        abs_paths.sort_unstable();
2774        abs_paths.dedup_by(|a, b| a.starts_with(&b));
2775
2776        let root_abs_path = self.snapshot.lock().abs_path.clone();
2777        let root_canonical_path = self.fs.canonicalize(&root_abs_path).await.log_err()?;
2778        let metadata = futures::future::join_all(
2779            abs_paths
2780                .iter()
2781                .map(|abs_path| self.fs.metadata(&abs_path))
2782                .collect::<Vec<_>>(),
2783        )
2784        .await;
2785
2786        let mut snapshot = self.snapshot.lock();
2787        let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
2788        snapshot.scan_id += 1;
2789        if is_idle && !doing_recursive_update {
2790            snapshot.completed_scan_id = snapshot.scan_id;
2791        }
2792
2793        // Remove any entries for paths that no longer exist or are being recursively
2794        // refreshed. Do this before adding any new entries, so that renames can be
2795        // detected regardless of the order of the paths.
2796        let mut event_paths = Vec::<Arc<Path>>::with_capacity(abs_paths.len());
2797        for (abs_path, metadata) in abs_paths.iter().zip(metadata.iter()) {
2798            if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
2799                if matches!(metadata, Ok(None)) || doing_recursive_update {
2800                    snapshot.remove_path(path);
2801                }
2802                event_paths.push(path.into());
2803            } else {
2804                log::error!(
2805                    "unexpected event {:?} for root path {:?}",
2806                    abs_path,
2807                    root_canonical_path
2808                );
2809            }
2810        }
2811
2812        for (path, metadata) in event_paths.iter().cloned().zip(metadata.into_iter()) {
2813            let abs_path: Arc<Path> = root_abs_path.join(&path).into();
2814
2815            match metadata {
2816                Ok(Some(metadata)) => {
2817                    let ignore_stack =
2818                        snapshot.ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
2819                    let mut fs_entry = Entry::new(
2820                        path.clone(),
2821                        &metadata,
2822                        snapshot.next_entry_id.as_ref(),
2823                        snapshot.root_char_bag,
2824                    );
2825                    fs_entry.is_ignored = ignore_stack.is_all();
2826                    snapshot.insert_entry(fs_entry, self.fs.as_ref());
2827
2828                    let scan_id = snapshot.scan_id;
2829
2830                    let repo_with_path_in_dotgit = snapshot.repo_for_metadata(&path);
2831                    if let Some((entry_id, repo)) = repo_with_path_in_dotgit {
2832                        let work_dir = snapshot
2833                            .entry_for_id(entry_id)
2834                            .map(|entry| RepositoryWorkDirectory(entry.path.clone()))?;
2835
2836                        let repo = repo.lock();
2837                        repo.reload_index();
2838                        let branch = repo.branch_name();
2839
2840                        snapshot.git_repositories.update(&entry_id, |entry| {
2841                            entry.scan_id = scan_id;
2842                        });
2843
2844                        snapshot
2845                            .repository_entries
2846                            .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
2847                    }
2848
2849                    if let Some(scan_queue_tx) = &scan_queue_tx {
2850                        let mut ancestor_inodes = snapshot.ancestor_inodes_for_path(&path);
2851                        if metadata.is_dir && !ancestor_inodes.contains(&metadata.inode) {
2852                            ancestor_inodes.insert(metadata.inode);
2853                            smol::block_on(scan_queue_tx.send(ScanJob {
2854                                abs_path,
2855                                path,
2856                                ignore_stack,
2857                                ancestor_inodes,
2858                                scan_queue: scan_queue_tx.clone(),
2859                            }))
2860                            .unwrap();
2861                        }
2862                    }
2863                }
2864                Ok(None) => {}
2865                Err(err) => {
2866                    // TODO - create a special 'error' entry in the entries tree to mark this
2867                    log::error!("error reading file on event {:?}", err);
2868                }
2869            }
2870        }
2871
2872        Some(event_paths)
2873    }
2874
2875    async fn update_ignore_statuses(&self) {
2876        use futures::FutureExt as _;
2877
2878        let mut snapshot = self.snapshot.lock().clone();
2879        let mut ignores_to_update = Vec::new();
2880        let mut ignores_to_delete = Vec::new();
2881        for (parent_abs_path, (_, scan_id)) in &snapshot.ignores_by_parent_abs_path {
2882            if let Ok(parent_path) = parent_abs_path.strip_prefix(&snapshot.abs_path) {
2883                if *scan_id > snapshot.completed_scan_id
2884                    && snapshot.entry_for_path(parent_path).is_some()
2885                {
2886                    ignores_to_update.push(parent_abs_path.clone());
2887                }
2888
2889                let ignore_path = parent_path.join(&*GITIGNORE);
2890                if snapshot.entry_for_path(ignore_path).is_none() {
2891                    ignores_to_delete.push(parent_abs_path.clone());
2892                }
2893            }
2894        }
2895
2896        for parent_abs_path in ignores_to_delete {
2897            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
2898            self.snapshot
2899                .lock()
2900                .ignores_by_parent_abs_path
2901                .remove(&parent_abs_path);
2902        }
2903
2904        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
2905        ignores_to_update.sort_unstable();
2906        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
2907        while let Some(parent_abs_path) = ignores_to_update.next() {
2908            while ignores_to_update
2909                .peek()
2910                .map_or(false, |p| p.starts_with(&parent_abs_path))
2911            {
2912                ignores_to_update.next().unwrap();
2913            }
2914
2915            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
2916            smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
2917                abs_path: parent_abs_path,
2918                ignore_stack,
2919                ignore_queue: ignore_queue_tx.clone(),
2920            }))
2921            .unwrap();
2922        }
2923        drop(ignore_queue_tx);
2924
2925        self.executor
2926            .scoped(|scope| {
2927                for _ in 0..self.executor.num_cpus() {
2928                    scope.spawn(async {
2929                        loop {
2930                            select_biased! {
2931                                // Process any path refresh requests before moving on to process
2932                                // the queue of ignore statuses.
2933                                request = self.refresh_requests_rx.recv().fuse() => {
2934                                    let Ok((paths, barrier)) = request else { break };
2935                                    if !self.process_refresh_request(paths, barrier).await {
2936                                        return;
2937                                    }
2938                                }
2939
2940                                // Recursively process directories whose ignores have changed.
2941                                job = ignore_queue_rx.recv().fuse() => {
2942                                    let Ok(job) = job else { break };
2943                                    self.update_ignore_status(job, &snapshot).await;
2944                                }
2945                            }
2946                        }
2947                    });
2948                }
2949            })
2950            .await;
2951    }
2952
2953    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
2954        let mut ignore_stack = job.ignore_stack;
2955        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
2956            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
2957        }
2958
2959        let mut entries_by_id_edits = Vec::new();
2960        let mut entries_by_path_edits = Vec::new();
2961        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
2962        for mut entry in snapshot.child_entries(path).cloned() {
2963            let was_ignored = entry.is_ignored;
2964            let abs_path = snapshot.abs_path().join(&entry.path);
2965            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
2966            if entry.is_dir() {
2967                let child_ignore_stack = if entry.is_ignored {
2968                    IgnoreStack::all()
2969                } else {
2970                    ignore_stack.clone()
2971                };
2972                job.ignore_queue
2973                    .send(UpdateIgnoreStatusJob {
2974                        abs_path: abs_path.into(),
2975                        ignore_stack: child_ignore_stack,
2976                        ignore_queue: job.ignore_queue.clone(),
2977                    })
2978                    .await
2979                    .unwrap();
2980            }
2981
2982            if entry.is_ignored != was_ignored {
2983                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
2984                path_entry.scan_id = snapshot.scan_id;
2985                path_entry.is_ignored = entry.is_ignored;
2986                entries_by_id_edits.push(Edit::Insert(path_entry));
2987                entries_by_path_edits.push(Edit::Insert(entry));
2988            }
2989        }
2990
2991        let mut snapshot = self.snapshot.lock();
2992        snapshot.entries_by_path.edit(entries_by_path_edits, &());
2993        snapshot.entries_by_id.edit(entries_by_id_edits, &());
2994    }
2995
2996    fn build_change_set(
2997        &self,
2998        old_snapshot: &Snapshot,
2999        new_snapshot: &Snapshot,
3000        event_paths: Vec<Arc<Path>>,
3001    ) -> HashMap<Arc<Path>, PathChange> {
3002        use PathChange::{Added, AddedOrUpdated, Removed, Updated};
3003
3004        let mut changes = HashMap::default();
3005        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
3006        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
3007        let received_before_initialized = !self.finished_initial_scan;
3008
3009        for path in event_paths {
3010            let path = PathKey(path);
3011            old_paths.seek(&path, Bias::Left, &());
3012            new_paths.seek(&path, Bias::Left, &());
3013
3014            loop {
3015                match (old_paths.item(), new_paths.item()) {
3016                    (Some(old_entry), Some(new_entry)) => {
3017                        if old_entry.path > path.0
3018                            && new_entry.path > path.0
3019                            && !old_entry.path.starts_with(&path.0)
3020                            && !new_entry.path.starts_with(&path.0)
3021                        {
3022                            break;
3023                        }
3024
3025                        match Ord::cmp(&old_entry.path, &new_entry.path) {
3026                            Ordering::Less => {
3027                                changes.insert(old_entry.path.clone(), Removed);
3028                                old_paths.next(&());
3029                            }
3030                            Ordering::Equal => {
3031                                if received_before_initialized {
3032                                    // If the worktree was not fully initialized when this event was generated,
3033                                    // we can't know whether this entry was added during the scan or whether
3034                                    // it was merely updated.
3035                                    changes.insert(new_entry.path.clone(), AddedOrUpdated);
3036                                } else if old_entry.mtime != new_entry.mtime {
3037                                    changes.insert(new_entry.path.clone(), Updated);
3038                                }
3039                                old_paths.next(&());
3040                                new_paths.next(&());
3041                            }
3042                            Ordering::Greater => {
3043                                changes.insert(new_entry.path.clone(), Added);
3044                                new_paths.next(&());
3045                            }
3046                        }
3047                    }
3048                    (Some(old_entry), None) => {
3049                        changes.insert(old_entry.path.clone(), Removed);
3050                        old_paths.next(&());
3051                    }
3052                    (None, Some(new_entry)) => {
3053                        changes.insert(new_entry.path.clone(), Added);
3054                        new_paths.next(&());
3055                    }
3056                    (None, None) => break,
3057                }
3058            }
3059        }
3060        changes
3061    }
3062
3063    async fn progress_timer(&self, running: bool) {
3064        if !running {
3065            return futures::future::pending().await;
3066        }
3067
3068        #[cfg(any(test, feature = "test-support"))]
3069        if self.fs.is_fake() {
3070            return self.executor.simulate_random_delay().await;
3071        }
3072
3073        smol::Timer::after(Duration::from_millis(100)).await;
3074    }
3075}
3076
3077fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
3078    let mut result = root_char_bag;
3079    result.extend(
3080        path.to_string_lossy()
3081            .chars()
3082            .map(|c| c.to_ascii_lowercase()),
3083    );
3084    result
3085}
3086
3087struct ScanJob {
3088    abs_path: Arc<Path>,
3089    path: Arc<Path>,
3090    ignore_stack: Arc<IgnoreStack>,
3091    scan_queue: Sender<ScanJob>,
3092    ancestor_inodes: TreeSet<u64>,
3093}
3094
3095struct UpdateIgnoreStatusJob {
3096    abs_path: Arc<Path>,
3097    ignore_stack: Arc<IgnoreStack>,
3098    ignore_queue: Sender<UpdateIgnoreStatusJob>,
3099}
3100
3101pub trait WorktreeHandle {
3102    #[cfg(any(test, feature = "test-support"))]
3103    fn flush_fs_events<'a>(
3104        &self,
3105        cx: &'a gpui::TestAppContext,
3106    ) -> futures::future::LocalBoxFuture<'a, ()>;
3107}
3108
3109impl WorktreeHandle for ModelHandle<Worktree> {
3110    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
3111    // occurred before the worktree was constructed. These events can cause the worktree to perfrom
3112    // extra directory scans, and emit extra scan-state notifications.
3113    //
3114    // This function mutates the worktree's directory and waits for those mutations to be picked up,
3115    // to ensure that all redundant FS events have already been processed.
3116    #[cfg(any(test, feature = "test-support"))]
3117    fn flush_fs_events<'a>(
3118        &self,
3119        cx: &'a gpui::TestAppContext,
3120    ) -> futures::future::LocalBoxFuture<'a, ()> {
3121        use smol::future::FutureExt;
3122
3123        let filename = "fs-event-sentinel";
3124        let tree = self.clone();
3125        let (fs, root_path) = self.read_with(cx, |tree, _| {
3126            let tree = tree.as_local().unwrap();
3127            (tree.fs.clone(), tree.abs_path().clone())
3128        });
3129
3130        async move {
3131            fs.create_file(&root_path.join(filename), Default::default())
3132                .await
3133                .unwrap();
3134            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_some())
3135                .await;
3136
3137            fs.remove_file(&root_path.join(filename), Default::default())
3138                .await
3139                .unwrap();
3140            tree.condition(cx, |tree, _| tree.entry_for_path(filename).is_none())
3141                .await;
3142
3143            cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3144                .await;
3145        }
3146        .boxed_local()
3147    }
3148}
3149
3150#[derive(Clone, Debug)]
3151struct TraversalProgress<'a> {
3152    max_path: &'a Path,
3153    count: usize,
3154    visible_count: usize,
3155    file_count: usize,
3156    visible_file_count: usize,
3157}
3158
3159impl<'a> TraversalProgress<'a> {
3160    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
3161        match (include_ignored, include_dirs) {
3162            (true, true) => self.count,
3163            (true, false) => self.file_count,
3164            (false, true) => self.visible_count,
3165            (false, false) => self.visible_file_count,
3166        }
3167    }
3168}
3169
3170impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
3171    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3172        self.max_path = summary.max_path.as_ref();
3173        self.count += summary.count;
3174        self.visible_count += summary.visible_count;
3175        self.file_count += summary.file_count;
3176        self.visible_file_count += summary.visible_file_count;
3177    }
3178}
3179
3180impl<'a> Default for TraversalProgress<'a> {
3181    fn default() -> Self {
3182        Self {
3183            max_path: Path::new(""),
3184            count: 0,
3185            visible_count: 0,
3186            file_count: 0,
3187            visible_file_count: 0,
3188        }
3189    }
3190}
3191
3192pub struct Traversal<'a> {
3193    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
3194    include_ignored: bool,
3195    include_dirs: bool,
3196}
3197
3198impl<'a> Traversal<'a> {
3199    pub fn advance(&mut self) -> bool {
3200        self.advance_to_offset(self.offset() + 1)
3201    }
3202
3203    pub fn advance_to_offset(&mut self, offset: usize) -> bool {
3204        self.cursor.seek_forward(
3205            &TraversalTarget::Count {
3206                count: offset,
3207                include_dirs: self.include_dirs,
3208                include_ignored: self.include_ignored,
3209            },
3210            Bias::Right,
3211            &(),
3212        )
3213    }
3214
3215    pub fn advance_to_sibling(&mut self) -> bool {
3216        while let Some(entry) = self.cursor.item() {
3217            self.cursor.seek_forward(
3218                &TraversalTarget::PathSuccessor(&entry.path),
3219                Bias::Left,
3220                &(),
3221            );
3222            if let Some(entry) = self.cursor.item() {
3223                if (self.include_dirs || !entry.is_dir())
3224                    && (self.include_ignored || !entry.is_ignored)
3225                {
3226                    return true;
3227                }
3228            }
3229        }
3230        false
3231    }
3232
3233    pub fn entry(&self) -> Option<&'a Entry> {
3234        self.cursor.item()
3235    }
3236
3237    pub fn offset(&self) -> usize {
3238        self.cursor
3239            .start()
3240            .count(self.include_dirs, self.include_ignored)
3241    }
3242}
3243
3244impl<'a> Iterator for Traversal<'a> {
3245    type Item = &'a Entry;
3246
3247    fn next(&mut self) -> Option<Self::Item> {
3248        if let Some(item) = self.entry() {
3249            self.advance();
3250            Some(item)
3251        } else {
3252            None
3253        }
3254    }
3255}
3256
3257#[derive(Debug)]
3258enum TraversalTarget<'a> {
3259    Path(&'a Path),
3260    PathSuccessor(&'a Path),
3261    Count {
3262        count: usize,
3263        include_ignored: bool,
3264        include_dirs: bool,
3265    },
3266}
3267
3268impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
3269    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
3270        match self {
3271            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
3272            TraversalTarget::PathSuccessor(path) => {
3273                if !cursor_location.max_path.starts_with(path) {
3274                    Ordering::Equal
3275                } else {
3276                    Ordering::Greater
3277                }
3278            }
3279            TraversalTarget::Count {
3280                count,
3281                include_dirs,
3282                include_ignored,
3283            } => Ord::cmp(
3284                count,
3285                &cursor_location.count(*include_dirs, *include_ignored),
3286            ),
3287        }
3288    }
3289}
3290
3291struct ChildEntriesIter<'a> {
3292    parent_path: &'a Path,
3293    traversal: Traversal<'a>,
3294}
3295
3296impl<'a> Iterator for ChildEntriesIter<'a> {
3297    type Item = &'a Entry;
3298
3299    fn next(&mut self) -> Option<Self::Item> {
3300        if let Some(item) = self.traversal.entry() {
3301            if item.path.starts_with(&self.parent_path) {
3302                self.traversal.advance_to_sibling();
3303                return Some(item);
3304            }
3305        }
3306        None
3307    }
3308}
3309
3310impl<'a> From<&'a Entry> for proto::Entry {
3311    fn from(entry: &'a Entry) -> Self {
3312        Self {
3313            id: entry.id.to_proto(),
3314            is_dir: entry.is_dir(),
3315            path: entry.path.to_string_lossy().into(),
3316            inode: entry.inode,
3317            mtime: Some(entry.mtime.into()),
3318            is_symlink: entry.is_symlink,
3319            is_ignored: entry.is_ignored,
3320        }
3321    }
3322}
3323
3324impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
3325    type Error = anyhow::Error;
3326
3327    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
3328        if let Some(mtime) = entry.mtime {
3329            let kind = if entry.is_dir {
3330                EntryKind::Dir
3331            } else {
3332                let mut char_bag = *root_char_bag;
3333                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
3334                EntryKind::File(char_bag)
3335            };
3336            let path: Arc<Path> = PathBuf::from(entry.path).into();
3337            Ok(Entry {
3338                id: ProjectEntryId::from_proto(entry.id),
3339                kind,
3340                path,
3341                inode: entry.inode,
3342                mtime: mtime.into(),
3343                is_symlink: entry.is_symlink,
3344                is_ignored: entry.is_ignored,
3345            })
3346        } else {
3347            Err(anyhow!(
3348                "missing mtime in remote worktree entry {:?}",
3349                entry.path
3350            ))
3351        }
3352    }
3353}
3354
3355#[cfg(test)]
3356mod tests {
3357    use super::*;
3358    use fs::{FakeFs, RealFs};
3359    use gpui::{executor::Deterministic, TestAppContext};
3360    use pretty_assertions::assert_eq;
3361    use rand::prelude::*;
3362    use serde_json::json;
3363    use std::{env, fmt::Write};
3364    use util::{http::FakeHttpClient, test::temp_tree};
3365
3366    #[gpui::test]
3367    async fn test_traversal(cx: &mut TestAppContext) {
3368        let fs = FakeFs::new(cx.background());
3369        fs.insert_tree(
3370            "/root",
3371            json!({
3372               ".gitignore": "a/b\n",
3373               "a": {
3374                   "b": "",
3375                   "c": "",
3376               }
3377            }),
3378        )
3379        .await;
3380
3381        let http_client = FakeHttpClient::with_404_response();
3382        let client = cx.read(|cx| Client::new(http_client, cx));
3383
3384        let tree = Worktree::local(
3385            client,
3386            Path::new("/root"),
3387            true,
3388            fs,
3389            Default::default(),
3390            &mut cx.to_async(),
3391        )
3392        .await
3393        .unwrap();
3394        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3395            .await;
3396
3397        tree.read_with(cx, |tree, _| {
3398            assert_eq!(
3399                tree.entries(false)
3400                    .map(|entry| entry.path.as_ref())
3401                    .collect::<Vec<_>>(),
3402                vec![
3403                    Path::new(""),
3404                    Path::new(".gitignore"),
3405                    Path::new("a"),
3406                    Path::new("a/c"),
3407                ]
3408            );
3409            assert_eq!(
3410                tree.entries(true)
3411                    .map(|entry| entry.path.as_ref())
3412                    .collect::<Vec<_>>(),
3413                vec![
3414                    Path::new(""),
3415                    Path::new(".gitignore"),
3416                    Path::new("a"),
3417                    Path::new("a/b"),
3418                    Path::new("a/c"),
3419                ]
3420            );
3421        })
3422    }
3423
3424    #[gpui::test(iterations = 10)]
3425    async fn test_circular_symlinks(executor: Arc<Deterministic>, cx: &mut TestAppContext) {
3426        let fs = FakeFs::new(cx.background());
3427        fs.insert_tree(
3428            "/root",
3429            json!({
3430                "lib": {
3431                    "a": {
3432                        "a.txt": ""
3433                    },
3434                    "b": {
3435                        "b.txt": ""
3436                    }
3437                }
3438            }),
3439        )
3440        .await;
3441        fs.insert_symlink("/root/lib/a/lib", "..".into()).await;
3442        fs.insert_symlink("/root/lib/b/lib", "..".into()).await;
3443
3444        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3445        let tree = Worktree::local(
3446            client,
3447            Path::new("/root"),
3448            true,
3449            fs.clone(),
3450            Default::default(),
3451            &mut cx.to_async(),
3452        )
3453        .await
3454        .unwrap();
3455
3456        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3457            .await;
3458
3459        tree.read_with(cx, |tree, _| {
3460            assert_eq!(
3461                tree.entries(false)
3462                    .map(|entry| entry.path.as_ref())
3463                    .collect::<Vec<_>>(),
3464                vec![
3465                    Path::new(""),
3466                    Path::new("lib"),
3467                    Path::new("lib/a"),
3468                    Path::new("lib/a/a.txt"),
3469                    Path::new("lib/a/lib"),
3470                    Path::new("lib/b"),
3471                    Path::new("lib/b/b.txt"),
3472                    Path::new("lib/b/lib"),
3473                ]
3474            );
3475        });
3476
3477        fs.rename(
3478            Path::new("/root/lib/a/lib"),
3479            Path::new("/root/lib/a/lib-2"),
3480            Default::default(),
3481        )
3482        .await
3483        .unwrap();
3484        executor.run_until_parked();
3485        tree.read_with(cx, |tree, _| {
3486            assert_eq!(
3487                tree.entries(false)
3488                    .map(|entry| entry.path.as_ref())
3489                    .collect::<Vec<_>>(),
3490                vec![
3491                    Path::new(""),
3492                    Path::new("lib"),
3493                    Path::new("lib/a"),
3494                    Path::new("lib/a/a.txt"),
3495                    Path::new("lib/a/lib-2"),
3496                    Path::new("lib/b"),
3497                    Path::new("lib/b/b.txt"),
3498                    Path::new("lib/b/lib"),
3499                ]
3500            );
3501        });
3502    }
3503
3504    #[gpui::test]
3505    async fn test_rescan_with_gitignore(cx: &mut TestAppContext) {
3506        let parent_dir = temp_tree(json!({
3507            ".gitignore": "ancestor-ignored-file1\nancestor-ignored-file2\n",
3508            "tree": {
3509                ".git": {},
3510                ".gitignore": "ignored-dir\n",
3511                "tracked-dir": {
3512                    "tracked-file1": "",
3513                    "ancestor-ignored-file1": "",
3514                },
3515                "ignored-dir": {
3516                    "ignored-file1": ""
3517                }
3518            }
3519        }));
3520        let dir = parent_dir.path().join("tree");
3521
3522        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3523
3524        let tree = Worktree::local(
3525            client,
3526            dir.as_path(),
3527            true,
3528            Arc::new(RealFs),
3529            Default::default(),
3530            &mut cx.to_async(),
3531        )
3532        .await
3533        .unwrap();
3534        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3535            .await;
3536        tree.flush_fs_events(cx).await;
3537        cx.read(|cx| {
3538            let tree = tree.read(cx);
3539            assert!(
3540                !tree
3541                    .entry_for_path("tracked-dir/tracked-file1")
3542                    .unwrap()
3543                    .is_ignored
3544            );
3545            assert!(
3546                tree.entry_for_path("tracked-dir/ancestor-ignored-file1")
3547                    .unwrap()
3548                    .is_ignored
3549            );
3550            assert!(
3551                tree.entry_for_path("ignored-dir/ignored-file1")
3552                    .unwrap()
3553                    .is_ignored
3554            );
3555        });
3556
3557        std::fs::write(dir.join("tracked-dir/tracked-file2"), "").unwrap();
3558        std::fs::write(dir.join("tracked-dir/ancestor-ignored-file2"), "").unwrap();
3559        std::fs::write(dir.join("ignored-dir/ignored-file2"), "").unwrap();
3560        tree.flush_fs_events(cx).await;
3561        cx.read(|cx| {
3562            let tree = tree.read(cx);
3563            assert!(
3564                !tree
3565                    .entry_for_path("tracked-dir/tracked-file2")
3566                    .unwrap()
3567                    .is_ignored
3568            );
3569            assert!(
3570                tree.entry_for_path("tracked-dir/ancestor-ignored-file2")
3571                    .unwrap()
3572                    .is_ignored
3573            );
3574            assert!(
3575                tree.entry_for_path("ignored-dir/ignored-file2")
3576                    .unwrap()
3577                    .is_ignored
3578            );
3579            assert!(tree.entry_for_path(".git").unwrap().is_ignored);
3580        });
3581    }
3582
3583    #[gpui::test]
3584    async fn test_git_repository_for_path(cx: &mut TestAppContext) {
3585        let root = temp_tree(json!({
3586            "dir1": {
3587                ".git": {},
3588                "deps": {
3589                    "dep1": {
3590                        ".git": {},
3591                        "src": {
3592                            "a.txt": ""
3593                        }
3594                    }
3595                },
3596                "src": {
3597                    "b.txt": ""
3598                }
3599            },
3600            "c.txt": "",
3601        }));
3602
3603        let http_client = FakeHttpClient::with_404_response();
3604        let client = cx.read(|cx| Client::new(http_client, cx));
3605        let tree = Worktree::local(
3606            client,
3607            root.path(),
3608            true,
3609            Arc::new(RealFs),
3610            Default::default(),
3611            &mut cx.to_async(),
3612        )
3613        .await
3614        .unwrap();
3615
3616        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3617            .await;
3618        tree.flush_fs_events(cx).await;
3619
3620        tree.read_with(cx, |tree, _cx| {
3621            let tree = tree.as_local().unwrap();
3622
3623            assert!(tree.repo_for("c.txt".as_ref()).is_none());
3624
3625            let entry = tree.repo_for("dir1/src/b.txt".as_ref()).unwrap();
3626            assert_eq!(
3627                entry
3628                    .work_directory(tree)
3629                    .map(|directory| directory.as_ref().to_owned()),
3630                Some(Path::new("dir1").to_owned())
3631            );
3632
3633            let entry = tree.repo_for("dir1/deps/dep1/src/a.txt".as_ref()).unwrap();
3634            assert_eq!(
3635                entry
3636                    .work_directory(tree)
3637                    .map(|directory| directory.as_ref().to_owned()),
3638                Some(Path::new("dir1/deps/dep1").to_owned())
3639            );
3640        });
3641
3642        let repo_update_events = Arc::new(Mutex::new(vec![]));
3643        tree.update(cx, |_, cx| {
3644            let repo_update_events = repo_update_events.clone();
3645            cx.subscribe(&tree, move |_, _, event, _| {
3646                if let Event::UpdatedGitRepositories(update) = event {
3647                    repo_update_events.lock().push(update.clone());
3648                }
3649            })
3650            .detach();
3651        });
3652
3653        std::fs::write(root.path().join("dir1/.git/random_new_file"), "hello").unwrap();
3654        tree.flush_fs_events(cx).await;
3655
3656        assert_eq!(
3657            repo_update_events.lock()[0]
3658                .keys()
3659                .cloned()
3660                .collect::<Vec<Arc<Path>>>(),
3661            vec![Path::new("dir1").into()]
3662        );
3663
3664        std::fs::remove_dir_all(root.path().join("dir1/.git")).unwrap();
3665        tree.flush_fs_events(cx).await;
3666
3667        tree.read_with(cx, |tree, _cx| {
3668            let tree = tree.as_local().unwrap();
3669
3670            assert!(tree.repo_for("dir1/src/b.txt".as_ref()).is_none());
3671        });
3672    }
3673
3674    // #[test]
3675    // fn test_changed_repos() {
3676    //     fn fake_entry(work_dir_id: usize, scan_id: usize) -> RepositoryEntry {
3677    //         RepositoryEntry {
3678    //             scan_id,
3679    //             work_directory: ProjectEntryId(work_dir_id).into(),
3680    //             branch: None,
3681    //         }
3682    //     }
3683
3684    //     let mut prev_repos = TreeMap::<RepositoryWorkDirectory, RepositoryEntry>::default();
3685    //     prev_repos.insert(
3686    //         RepositoryWorkDirectory(Path::new("don't-care-1").into()),
3687    //         fake_entry(1, 0),
3688    //     );
3689    //     prev_repos.insert(
3690    //         RepositoryWorkDirectory(Path::new("don't-care-2").into()),
3691    //         fake_entry(2, 0),
3692    //     );
3693    //     prev_repos.insert(
3694    //         RepositoryWorkDirectory(Path::new("don't-care-3").into()),
3695    //         fake_entry(3, 0),
3696    //     );
3697
3698    //     let mut new_repos = TreeMap::<RepositoryWorkDirectory, RepositoryEntry>::default();
3699    //     new_repos.insert(
3700    //         RepositoryWorkDirectory(Path::new("don't-care-4").into()),
3701    //         fake_entry(2, 1),
3702    //     );
3703    //     new_repos.insert(
3704    //         RepositoryWorkDirectory(Path::new("don't-care-5").into()),
3705    //         fake_entry(3, 0),
3706    //     );
3707    //     new_repos.insert(
3708    //         RepositoryWorkDirectory(Path::new("don't-care-6").into()),
3709    //         fake_entry(4, 0),
3710    //     );
3711
3712    //     let res = LocalWorktree::changed_repos(&prev_repos, &new_repos);
3713
3714    //     // Deletion retained
3715    //     assert!(res
3716    //         .iter()
3717    //         .find(|repo| repo.work_directory.0 .0 == 1 && repo.scan_id == 0)
3718    //         .is_some());
3719
3720    //     // Update retained
3721    //     assert!(res
3722    //         .iter()
3723    //         .find(|repo| repo.work_directory.0 .0 == 2 && repo.scan_id == 1)
3724    //         .is_some());
3725
3726    //     // Addition retained
3727    //     assert!(res
3728    //         .iter()
3729    //         .find(|repo| repo.work_directory.0 .0 == 4 && repo.scan_id == 0)
3730    //         .is_some());
3731
3732    //     // Nochange, not retained
3733    //     assert!(res
3734    //         .iter()
3735    //         .find(|repo| repo.work_directory.0 .0 == 3 && repo.scan_id == 0)
3736    //         .is_none());
3737    // }
3738
3739    #[gpui::test]
3740    async fn test_write_file(cx: &mut TestAppContext) {
3741        let dir = temp_tree(json!({
3742            ".git": {},
3743            ".gitignore": "ignored-dir\n",
3744            "tracked-dir": {},
3745            "ignored-dir": {}
3746        }));
3747
3748        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3749
3750        let tree = Worktree::local(
3751            client,
3752            dir.path(),
3753            true,
3754            Arc::new(RealFs),
3755            Default::default(),
3756            &mut cx.to_async(),
3757        )
3758        .await
3759        .unwrap();
3760        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3761            .await;
3762        tree.flush_fs_events(cx).await;
3763
3764        tree.update(cx, |tree, cx| {
3765            tree.as_local().unwrap().write_file(
3766                Path::new("tracked-dir/file.txt"),
3767                "hello".into(),
3768                Default::default(),
3769                cx,
3770            )
3771        })
3772        .await
3773        .unwrap();
3774        tree.update(cx, |tree, cx| {
3775            tree.as_local().unwrap().write_file(
3776                Path::new("ignored-dir/file.txt"),
3777                "world".into(),
3778                Default::default(),
3779                cx,
3780            )
3781        })
3782        .await
3783        .unwrap();
3784
3785        tree.read_with(cx, |tree, _| {
3786            let tracked = tree.entry_for_path("tracked-dir/file.txt").unwrap();
3787            let ignored = tree.entry_for_path("ignored-dir/file.txt").unwrap();
3788            assert!(!tracked.is_ignored);
3789            assert!(ignored.is_ignored);
3790        });
3791    }
3792
3793    #[gpui::test(iterations = 30)]
3794    async fn test_create_directory_during_initial_scan(cx: &mut TestAppContext) {
3795        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3796
3797        let fs = FakeFs::new(cx.background());
3798        fs.insert_tree(
3799            "/root",
3800            json!({
3801                "b": {},
3802                "c": {},
3803                "d": {},
3804            }),
3805        )
3806        .await;
3807
3808        let tree = Worktree::local(
3809            client,
3810            "/root".as_ref(),
3811            true,
3812            fs,
3813            Default::default(),
3814            &mut cx.to_async(),
3815        )
3816        .await
3817        .unwrap();
3818
3819        let mut snapshot1 = tree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
3820
3821        let entry = tree
3822            .update(cx, |tree, cx| {
3823                tree.as_local_mut()
3824                    .unwrap()
3825                    .create_entry("a/e".as_ref(), true, cx)
3826            })
3827            .await
3828            .unwrap();
3829        assert!(entry.is_dir());
3830
3831        cx.foreground().run_until_parked();
3832        tree.read_with(cx, |tree, _| {
3833            assert_eq!(tree.entry_for_path("a/e").unwrap().kind, EntryKind::Dir);
3834        });
3835
3836        let snapshot2 = tree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
3837        let update = snapshot2.build_update(&snapshot1, 0, 0, true);
3838        snapshot1.apply_remote_update(update).unwrap();
3839        assert_eq!(snapshot1.to_vec(true), snapshot2.to_vec(true),);
3840    }
3841
3842    #[gpui::test(iterations = 100)]
3843    async fn test_random_worktree_operations_during_initial_scan(
3844        cx: &mut TestAppContext,
3845        mut rng: StdRng,
3846    ) {
3847        let operations = env::var("OPERATIONS")
3848            .map(|o| o.parse().unwrap())
3849            .unwrap_or(5);
3850        let initial_entries = env::var("INITIAL_ENTRIES")
3851            .map(|o| o.parse().unwrap())
3852            .unwrap_or(20);
3853
3854        let root_dir = Path::new("/test");
3855        let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
3856        fs.as_fake().insert_tree(root_dir, json!({})).await;
3857        for _ in 0..initial_entries {
3858            randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
3859        }
3860        log::info!("generated initial tree");
3861
3862        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3863        let worktree = Worktree::local(
3864            client.clone(),
3865            root_dir,
3866            true,
3867            fs.clone(),
3868            Default::default(),
3869            &mut cx.to_async(),
3870        )
3871        .await
3872        .unwrap();
3873
3874        let mut snapshot = worktree.update(cx, |tree, _| tree.as_local().unwrap().snapshot());
3875
3876        for _ in 0..operations {
3877            worktree
3878                .update(cx, |worktree, cx| {
3879                    randomly_mutate_worktree(worktree, &mut rng, cx)
3880                })
3881                .await
3882                .log_err();
3883            worktree.read_with(cx, |tree, _| {
3884                tree.as_local().unwrap().snapshot.check_invariants()
3885            });
3886
3887            if rng.gen_bool(0.6) {
3888                let new_snapshot =
3889                    worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3890                let update = new_snapshot.build_update(&snapshot, 0, 0, true);
3891                snapshot.apply_remote_update(update.clone()).unwrap();
3892                assert_eq!(
3893                    snapshot.to_vec(true),
3894                    new_snapshot.to_vec(true),
3895                    "incorrect snapshot after update {:?}",
3896                    update
3897                );
3898            }
3899        }
3900
3901        worktree
3902            .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
3903            .await;
3904        worktree.read_with(cx, |tree, _| {
3905            tree.as_local().unwrap().snapshot.check_invariants()
3906        });
3907
3908        let new_snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
3909        let update = new_snapshot.build_update(&snapshot, 0, 0, true);
3910        snapshot.apply_remote_update(update.clone()).unwrap();
3911        assert_eq!(
3912            snapshot.to_vec(true),
3913            new_snapshot.to_vec(true),
3914            "incorrect snapshot after update {:?}",
3915            update
3916        );
3917    }
3918
3919    #[gpui::test(iterations = 100)]
3920    async fn test_random_worktree_changes(cx: &mut TestAppContext, mut rng: StdRng) {
3921        let operations = env::var("OPERATIONS")
3922            .map(|o| o.parse().unwrap())
3923            .unwrap_or(40);
3924        let initial_entries = env::var("INITIAL_ENTRIES")
3925            .map(|o| o.parse().unwrap())
3926            .unwrap_or(20);
3927
3928        let root_dir = Path::new("/test");
3929        let fs = FakeFs::new(cx.background()) as Arc<dyn Fs>;
3930        fs.as_fake().insert_tree(root_dir, json!({})).await;
3931        for _ in 0..initial_entries {
3932            randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
3933        }
3934        log::info!("generated initial tree");
3935
3936        let client = cx.read(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
3937        let worktree = Worktree::local(
3938            client.clone(),
3939            root_dir,
3940            true,
3941            fs.clone(),
3942            Default::default(),
3943            &mut cx.to_async(),
3944        )
3945        .await
3946        .unwrap();
3947
3948        worktree
3949            .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
3950            .await;
3951
3952        // After the initial scan is complete, the `UpdatedEntries` event can
3953        // be used to follow along with all changes to the worktree's snapshot.
3954        worktree.update(cx, |tree, cx| {
3955            let mut paths = tree
3956                .as_local()
3957                .unwrap()
3958                .paths()
3959                .cloned()
3960                .collect::<Vec<_>>();
3961
3962            cx.subscribe(&worktree, move |tree, _, event, _| {
3963                if let Event::UpdatedEntries(changes) = event {
3964                    for (path, change_type) in changes.iter() {
3965                        let path = path.clone();
3966                        let ix = match paths.binary_search(&path) {
3967                            Ok(ix) | Err(ix) => ix,
3968                        };
3969                        match change_type {
3970                            PathChange::Added => {
3971                                assert_ne!(paths.get(ix), Some(&path));
3972                                paths.insert(ix, path);
3973                            }
3974                            PathChange::Removed => {
3975                                assert_eq!(paths.get(ix), Some(&path));
3976                                paths.remove(ix);
3977                            }
3978                            PathChange::Updated => {
3979                                assert_eq!(paths.get(ix), Some(&path));
3980                            }
3981                            PathChange::AddedOrUpdated => {
3982                                if paths[ix] != path {
3983                                    paths.insert(ix, path);
3984                                }
3985                            }
3986                        }
3987                    }
3988                    let new_paths = tree.paths().cloned().collect::<Vec<_>>();
3989                    assert_eq!(paths, new_paths, "incorrect changes: {:?}", changes);
3990                }
3991            })
3992            .detach();
3993        });
3994
3995        let mut snapshots = Vec::new();
3996        let mut mutations_len = operations;
3997        while mutations_len > 1 {
3998            randomly_mutate_fs(&fs, root_dir, 1.0, &mut rng).await;
3999            let buffered_event_count = fs.as_fake().buffered_event_count().await;
4000            if buffered_event_count > 0 && rng.gen_bool(0.3) {
4001                let len = rng.gen_range(0..=buffered_event_count);
4002                log::info!("flushing {} events", len);
4003                fs.as_fake().flush_events(len).await;
4004            } else {
4005                randomly_mutate_fs(&fs, root_dir, 0.6, &mut rng).await;
4006                mutations_len -= 1;
4007            }
4008
4009            cx.foreground().run_until_parked();
4010            if rng.gen_bool(0.2) {
4011                log::info!("storing snapshot {}", snapshots.len());
4012                let snapshot =
4013                    worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4014                snapshots.push(snapshot);
4015            }
4016        }
4017
4018        log::info!("quiescing");
4019        fs.as_fake().flush_events(usize::MAX).await;
4020        cx.foreground().run_until_parked();
4021        let snapshot = worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4022        snapshot.check_invariants();
4023
4024        {
4025            let new_worktree = Worktree::local(
4026                client.clone(),
4027                root_dir,
4028                true,
4029                fs.clone(),
4030                Default::default(),
4031                &mut cx.to_async(),
4032            )
4033            .await
4034            .unwrap();
4035            new_worktree
4036                .update(cx, |tree, _| tree.as_local_mut().unwrap().scan_complete())
4037                .await;
4038            let new_snapshot =
4039                new_worktree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
4040            assert_eq!(snapshot.to_vec(true), new_snapshot.to_vec(true));
4041        }
4042
4043        for (i, mut prev_snapshot) in snapshots.into_iter().enumerate() {
4044            let include_ignored = rng.gen::<bool>();
4045            if !include_ignored {
4046                let mut entries_by_path_edits = Vec::new();
4047                let mut entries_by_id_edits = Vec::new();
4048                for entry in prev_snapshot
4049                    .entries_by_id
4050                    .cursor::<()>()
4051                    .filter(|e| e.is_ignored)
4052                {
4053                    entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
4054                    entries_by_id_edits.push(Edit::Remove(entry.id));
4055                }
4056
4057                prev_snapshot
4058                    .entries_by_path
4059                    .edit(entries_by_path_edits, &());
4060                prev_snapshot.entries_by_id.edit(entries_by_id_edits, &());
4061            }
4062
4063            let update = snapshot.build_update(&prev_snapshot, 0, 0, include_ignored);
4064            prev_snapshot.apply_remote_update(update.clone()).unwrap();
4065            assert_eq!(
4066                prev_snapshot.to_vec(include_ignored),
4067                snapshot.to_vec(include_ignored),
4068                "wrong update for snapshot {i}. update: {:?}",
4069                update
4070            );
4071        }
4072    }
4073
4074    fn randomly_mutate_worktree(
4075        worktree: &mut Worktree,
4076        rng: &mut impl Rng,
4077        cx: &mut ModelContext<Worktree>,
4078    ) -> Task<Result<()>> {
4079        let worktree = worktree.as_local_mut().unwrap();
4080        let snapshot = worktree.snapshot();
4081        let entry = snapshot.entries(false).choose(rng).unwrap();
4082
4083        match rng.gen_range(0_u32..100) {
4084            0..=33 if entry.path.as_ref() != Path::new("") => {
4085                log::info!("deleting entry {:?} ({})", entry.path, entry.id.0);
4086                worktree.delete_entry(entry.id, cx).unwrap()
4087            }
4088            ..=66 if entry.path.as_ref() != Path::new("") => {
4089                let other_entry = snapshot.entries(false).choose(rng).unwrap();
4090                let new_parent_path = if other_entry.is_dir() {
4091                    other_entry.path.clone()
4092                } else {
4093                    other_entry.path.parent().unwrap().into()
4094                };
4095                let mut new_path = new_parent_path.join(gen_name(rng));
4096                if new_path.starts_with(&entry.path) {
4097                    new_path = gen_name(rng).into();
4098                }
4099
4100                log::info!(
4101                    "renaming entry {:?} ({}) to {:?}",
4102                    entry.path,
4103                    entry.id.0,
4104                    new_path
4105                );
4106                let task = worktree.rename_entry(entry.id, new_path, cx).unwrap();
4107                cx.foreground().spawn(async move {
4108                    task.await?;
4109                    Ok(())
4110                })
4111            }
4112            _ => {
4113                let task = if entry.is_dir() {
4114                    let child_path = entry.path.join(gen_name(rng));
4115                    let is_dir = rng.gen_bool(0.3);
4116                    log::info!(
4117                        "creating {} at {:?}",
4118                        if is_dir { "dir" } else { "file" },
4119                        child_path,
4120                    );
4121                    worktree.create_entry(child_path, is_dir, cx)
4122                } else {
4123                    log::info!("overwriting file {:?} ({})", entry.path, entry.id.0);
4124                    worktree.write_file(entry.path.clone(), "".into(), Default::default(), cx)
4125                };
4126                cx.foreground().spawn(async move {
4127                    task.await?;
4128                    Ok(())
4129                })
4130            }
4131        }
4132    }
4133
4134    async fn randomly_mutate_fs(
4135        fs: &Arc<dyn Fs>,
4136        root_path: &Path,
4137        insertion_probability: f64,
4138        rng: &mut impl Rng,
4139    ) {
4140        let mut files = Vec::new();
4141        let mut dirs = Vec::new();
4142        for path in fs.as_fake().paths() {
4143            if path.starts_with(root_path) {
4144                if fs.is_file(&path).await {
4145                    files.push(path);
4146                } else {
4147                    dirs.push(path);
4148                }
4149            }
4150        }
4151
4152        if (files.is_empty() && dirs.len() == 1) || rng.gen_bool(insertion_probability) {
4153            let path = dirs.choose(rng).unwrap();
4154            let new_path = path.join(gen_name(rng));
4155
4156            if rng.gen() {
4157                log::info!(
4158                    "creating dir {:?}",
4159                    new_path.strip_prefix(root_path).unwrap()
4160                );
4161                fs.create_dir(&new_path).await.unwrap();
4162            } else {
4163                log::info!(
4164                    "creating file {:?}",
4165                    new_path.strip_prefix(root_path).unwrap()
4166                );
4167                fs.create_file(&new_path, Default::default()).await.unwrap();
4168            }
4169        } else if rng.gen_bool(0.05) {
4170            let ignore_dir_path = dirs.choose(rng).unwrap();
4171            let ignore_path = ignore_dir_path.join(&*GITIGNORE);
4172
4173            let subdirs = dirs
4174                .iter()
4175                .filter(|d| d.starts_with(&ignore_dir_path))
4176                .cloned()
4177                .collect::<Vec<_>>();
4178            let subfiles = files
4179                .iter()
4180                .filter(|d| d.starts_with(&ignore_dir_path))
4181                .cloned()
4182                .collect::<Vec<_>>();
4183            let files_to_ignore = {
4184                let len = rng.gen_range(0..=subfiles.len());
4185                subfiles.choose_multiple(rng, len)
4186            };
4187            let dirs_to_ignore = {
4188                let len = rng.gen_range(0..subdirs.len());
4189                subdirs.choose_multiple(rng, len)
4190            };
4191
4192            let mut ignore_contents = String::new();
4193            for path_to_ignore in files_to_ignore.chain(dirs_to_ignore) {
4194                writeln!(
4195                    ignore_contents,
4196                    "{}",
4197                    path_to_ignore
4198                        .strip_prefix(&ignore_dir_path)
4199                        .unwrap()
4200                        .to_str()
4201                        .unwrap()
4202                )
4203                .unwrap();
4204            }
4205            log::info!(
4206                "creating gitignore {:?} with contents:\n{}",
4207                ignore_path.strip_prefix(&root_path).unwrap(),
4208                ignore_contents
4209            );
4210            fs.save(
4211                &ignore_path,
4212                &ignore_contents.as_str().into(),
4213                Default::default(),
4214            )
4215            .await
4216            .unwrap();
4217        } else {
4218            let old_path = {
4219                let file_path = files.choose(rng);
4220                let dir_path = dirs[1..].choose(rng);
4221                file_path.into_iter().chain(dir_path).choose(rng).unwrap()
4222            };
4223
4224            let is_rename = rng.gen();
4225            if is_rename {
4226                let new_path_parent = dirs
4227                    .iter()
4228                    .filter(|d| !d.starts_with(old_path))
4229                    .choose(rng)
4230                    .unwrap();
4231
4232                let overwrite_existing_dir =
4233                    !old_path.starts_with(&new_path_parent) && rng.gen_bool(0.3);
4234                let new_path = if overwrite_existing_dir {
4235                    fs.remove_dir(
4236                        &new_path_parent,
4237                        RemoveOptions {
4238                            recursive: true,
4239                            ignore_if_not_exists: true,
4240                        },
4241                    )
4242                    .await
4243                    .unwrap();
4244                    new_path_parent.to_path_buf()
4245                } else {
4246                    new_path_parent.join(gen_name(rng))
4247                };
4248
4249                log::info!(
4250                    "renaming {:?} to {}{:?}",
4251                    old_path.strip_prefix(&root_path).unwrap(),
4252                    if overwrite_existing_dir {
4253                        "overwrite "
4254                    } else {
4255                        ""
4256                    },
4257                    new_path.strip_prefix(&root_path).unwrap()
4258                );
4259                fs.rename(
4260                    &old_path,
4261                    &new_path,
4262                    fs::RenameOptions {
4263                        overwrite: true,
4264                        ignore_if_exists: true,
4265                    },
4266                )
4267                .await
4268                .unwrap();
4269            } else if fs.is_file(&old_path).await {
4270                log::info!(
4271                    "deleting file {:?}",
4272                    old_path.strip_prefix(&root_path).unwrap()
4273                );
4274                fs.remove_file(old_path, Default::default()).await.unwrap();
4275            } else {
4276                log::info!(
4277                    "deleting dir {:?}",
4278                    old_path.strip_prefix(&root_path).unwrap()
4279                );
4280                fs.remove_dir(
4281                    &old_path,
4282                    RemoveOptions {
4283                        recursive: true,
4284                        ignore_if_not_exists: true,
4285                    },
4286                )
4287                .await
4288                .unwrap();
4289            }
4290        }
4291    }
4292
4293    fn gen_name(rng: &mut impl Rng) -> String {
4294        (0..6)
4295            .map(|_| rng.sample(rand::distributions::Alphanumeric))
4296            .map(char::from)
4297            .collect()
4298    }
4299
4300    impl LocalSnapshot {
4301        fn check_invariants(&self) {
4302            assert_eq!(
4303                self.entries_by_path
4304                    .cursor::<()>()
4305                    .map(|e| (&e.path, e.id))
4306                    .collect::<Vec<_>>(),
4307                self.entries_by_id
4308                    .cursor::<()>()
4309                    .map(|e| (&e.path, e.id))
4310                    .collect::<collections::BTreeSet<_>>()
4311                    .into_iter()
4312                    .collect::<Vec<_>>(),
4313                "entries_by_path and entries_by_id are inconsistent"
4314            );
4315
4316            let mut files = self.files(true, 0);
4317            let mut visible_files = self.files(false, 0);
4318            for entry in self.entries_by_path.cursor::<()>() {
4319                if entry.is_file() {
4320                    assert_eq!(files.next().unwrap().inode, entry.inode);
4321                    if !entry.is_ignored {
4322                        assert_eq!(visible_files.next().unwrap().inode, entry.inode);
4323                    }
4324                }
4325            }
4326
4327            assert!(files.next().is_none());
4328            assert!(visible_files.next().is_none());
4329
4330            let mut bfs_paths = Vec::new();
4331            let mut stack = vec![Path::new("")];
4332            while let Some(path) = stack.pop() {
4333                bfs_paths.push(path);
4334                let ix = stack.len();
4335                for child_entry in self.child_entries(path) {
4336                    stack.insert(ix, &child_entry.path);
4337                }
4338            }
4339
4340            let dfs_paths_via_iter = self
4341                .entries_by_path
4342                .cursor::<()>()
4343                .map(|e| e.path.as_ref())
4344                .collect::<Vec<_>>();
4345            assert_eq!(bfs_paths, dfs_paths_via_iter);
4346
4347            let dfs_paths_via_traversal = self
4348                .entries(true)
4349                .map(|e| e.path.as_ref())
4350                .collect::<Vec<_>>();
4351            assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
4352
4353            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
4354                let ignore_parent_path =
4355                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
4356                assert!(self.entry_for_path(&ignore_parent_path).is_some());
4357                assert!(self
4358                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
4359                    .is_some());
4360            }
4361        }
4362
4363        fn to_vec(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
4364            let mut paths = Vec::new();
4365            for entry in self.entries_by_path.cursor::<()>() {
4366                if include_ignored || !entry.is_ignored {
4367                    paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
4368                }
4369            }
4370            paths.sort_by(|a, b| a.0.cmp(b.0));
4371            paths
4372        }
4373    }
4374}