worktree.rs

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