worktree.rs

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