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