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