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 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();
 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    pub fn local_git_repo(&self, path: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
2120        self.local_repo_for_path(path)
2121            .map(|(_, entry)| entry.repo_ptr.clone())
2122    }
2123
2124    fn build_update(
2125        &self,
2126        project_id: u64,
2127        worktree_id: u64,
2128        entry_changes: UpdatedEntriesSet,
2129        repo_changes: UpdatedGitRepositoriesSet,
2130    ) -> proto::UpdateWorktree {
2131        let mut updated_entries = Vec::new();
2132        let mut removed_entries = Vec::new();
2133        let mut updated_repositories = Vec::new();
2134        let mut removed_repositories = Vec::new();
2135
2136        for (_, entry_id, path_change) in entry_changes.iter() {
2137            if let PathChange::Removed = path_change {
2138                removed_entries.push(entry_id.0 as u64);
2139            } else if let Some(entry) = self.entry_for_id(*entry_id) {
2140                updated_entries.push(proto::Entry::from(entry));
2141            }
2142        }
2143
2144        for (work_dir_path, change) in repo_changes.iter() {
2145            let new_repo = self
2146                .repository_entries
2147                .get(&RepositoryWorkDirectory(work_dir_path.clone()));
2148            match (&change.old_repository, new_repo) {
2149                (Some(old_repo), Some(new_repo)) => {
2150                    updated_repositories.push(new_repo.build_update(old_repo));
2151                }
2152                (None, Some(new_repo)) => {
2153                    updated_repositories.push(proto::RepositoryEntry::from(new_repo));
2154                }
2155                (Some(old_repo), None) => {
2156                    removed_repositories.push(old_repo.work_directory.0.to_proto());
2157                }
2158                _ => {}
2159            }
2160        }
2161
2162        removed_entries.sort_unstable();
2163        updated_entries.sort_unstable_by_key(|e| e.id);
2164        removed_repositories.sort_unstable();
2165        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2166
2167        // TODO - optimize, knowing that removed_entries are sorted.
2168        removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2169
2170        proto::UpdateWorktree {
2171            project_id,
2172            worktree_id,
2173            abs_path: self.abs_path().to_string_lossy().into(),
2174            root_name: self.root_name().to_string(),
2175            updated_entries,
2176            removed_entries,
2177            scan_id: self.scan_id as u64,
2178            is_last_update: self.completed_scan_id == self.scan_id,
2179            updated_repositories,
2180            removed_repositories,
2181        }
2182    }
2183
2184    fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
2185        let mut updated_entries = self
2186            .entries_by_path
2187            .iter()
2188            .map(proto::Entry::from)
2189            .collect::<Vec<_>>();
2190        updated_entries.sort_unstable_by_key(|e| e.id);
2191
2192        let mut updated_repositories = self
2193            .repository_entries
2194            .values()
2195            .map(proto::RepositoryEntry::from)
2196            .collect::<Vec<_>>();
2197        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2198
2199        proto::UpdateWorktree {
2200            project_id,
2201            worktree_id,
2202            abs_path: self.abs_path().to_string_lossy().into(),
2203            root_name: self.root_name().to_string(),
2204            updated_entries,
2205            removed_entries: Vec::new(),
2206            scan_id: self.scan_id as u64,
2207            is_last_update: self.completed_scan_id == self.scan_id,
2208            updated_repositories,
2209            removed_repositories: Vec::new(),
2210        }
2211    }
2212
2213    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2214        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2215            let abs_path = self.abs_path.join(&entry.path);
2216            match smol::block_on(build_gitignore(&abs_path, fs)) {
2217                Ok(ignore) => {
2218                    self.ignores_by_parent_abs_path
2219                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2220                }
2221                Err(error) => {
2222                    log::error!(
2223                        "error loading .gitignore file {:?} - {:?}",
2224                        &entry.path,
2225                        error
2226                    );
2227                }
2228            }
2229        }
2230
2231        if entry.kind == EntryKind::PendingDir {
2232            if let Some(existing_entry) =
2233                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2234            {
2235                entry.kind = existing_entry.kind;
2236            }
2237        }
2238
2239        let scan_id = self.scan_id;
2240        let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2241        if let Some(removed) = removed {
2242            if removed.id != entry.id {
2243                self.entries_by_id.remove(&removed.id, &());
2244            }
2245        }
2246        self.entries_by_id.insert_or_replace(
2247            PathEntry {
2248                id: entry.id,
2249                path: entry.path.clone(),
2250                is_ignored: entry.is_ignored,
2251                scan_id,
2252            },
2253            &(),
2254        );
2255
2256        entry
2257    }
2258
2259    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2260        let mut inodes = TreeSet::default();
2261        for ancestor in path.ancestors().skip(1) {
2262            if let Some(entry) = self.entry_for_path(ancestor) {
2263                inodes.insert(entry.inode);
2264            }
2265        }
2266        inodes
2267    }
2268
2269    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2270        let mut new_ignores = Vec::new();
2271        for (index, ancestor) in abs_path.ancestors().enumerate() {
2272            if index > 0 {
2273                if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2274                    new_ignores.push((ancestor, Some(ignore.clone())));
2275                } else {
2276                    new_ignores.push((ancestor, None));
2277                }
2278            }
2279            if ancestor.join(&*DOT_GIT).is_dir() {
2280                break;
2281            }
2282        }
2283
2284        let mut ignore_stack = IgnoreStack::none();
2285        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2286            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2287                ignore_stack = IgnoreStack::all();
2288                break;
2289            } else if let Some(ignore) = ignore {
2290                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2291            }
2292        }
2293
2294        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2295            ignore_stack = IgnoreStack::all();
2296        }
2297
2298        ignore_stack
2299    }
2300
2301    #[cfg(test)]
2302    pub(crate) fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2303        self.entries_by_path
2304            .cursor::<()>()
2305            .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2306    }
2307
2308    #[cfg(test)]
2309    pub fn check_invariants(&self, git_state: bool) {
2310        use pretty_assertions::assert_eq;
2311
2312        assert_eq!(
2313            self.entries_by_path
2314                .cursor::<()>()
2315                .map(|e| (&e.path, e.id))
2316                .collect::<Vec<_>>(),
2317            self.entries_by_id
2318                .cursor::<()>()
2319                .map(|e| (&e.path, e.id))
2320                .collect::<collections::BTreeSet<_>>()
2321                .into_iter()
2322                .collect::<Vec<_>>(),
2323            "entries_by_path and entries_by_id are inconsistent"
2324        );
2325
2326        let mut files = self.files(true, 0);
2327        let mut visible_files = self.files(false, 0);
2328        for entry in self.entries_by_path.cursor::<()>() {
2329            if entry.is_file() {
2330                assert_eq!(files.next().unwrap().inode, entry.inode);
2331                if !entry.is_ignored && !entry.is_external {
2332                    assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2333                }
2334            }
2335        }
2336
2337        assert!(files.next().is_none());
2338        assert!(visible_files.next().is_none());
2339
2340        let mut bfs_paths = Vec::new();
2341        let mut stack = self
2342            .root_entry()
2343            .map(|e| e.path.as_ref())
2344            .into_iter()
2345            .collect::<Vec<_>>();
2346        while let Some(path) = stack.pop() {
2347            bfs_paths.push(path);
2348            let ix = stack.len();
2349            for child_entry in self.child_entries(path) {
2350                stack.insert(ix, &child_entry.path);
2351            }
2352        }
2353
2354        let dfs_paths_via_iter = self
2355            .entries_by_path
2356            .cursor::<()>()
2357            .map(|e| e.path.as_ref())
2358            .collect::<Vec<_>>();
2359        assert_eq!(bfs_paths, dfs_paths_via_iter);
2360
2361        let dfs_paths_via_traversal = self
2362            .entries(true)
2363            .map(|e| e.path.as_ref())
2364            .collect::<Vec<_>>();
2365        assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2366
2367        if git_state {
2368            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2369                let ignore_parent_path =
2370                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
2371                assert!(self.entry_for_path(&ignore_parent_path).is_some());
2372                assert!(self
2373                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2374                    .is_some());
2375            }
2376        }
2377    }
2378
2379    #[cfg(test)]
2380    pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2381        let mut paths = Vec::new();
2382        for entry in self.entries_by_path.cursor::<()>() {
2383            if include_ignored || !entry.is_ignored {
2384                paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2385            }
2386        }
2387        paths.sort_by(|a, b| a.0.cmp(b.0));
2388        paths
2389    }
2390
2391    pub fn is_path_private(&self, path: &Path) -> bool {
2392        path.ancestors().any(|ancestor| {
2393            self.private_files
2394                .iter()
2395                .any(|exclude_matcher| exclude_matcher.is_match(&ancestor))
2396        })
2397    }
2398
2399    pub fn is_path_excluded(&self, mut path: PathBuf) -> bool {
2400        loop {
2401            if self
2402                .file_scan_exclusions
2403                .iter()
2404                .any(|exclude_matcher| exclude_matcher.is_match(&path))
2405            {
2406                return true;
2407            }
2408            if !path.pop() {
2409                return false;
2410            }
2411        }
2412    }
2413}
2414
2415impl BackgroundScannerState {
2416    fn should_scan_directory(&self, entry: &Entry) -> bool {
2417        (!entry.is_external && !entry.is_ignored)
2418            || entry.path.file_name() == Some(*DOT_GIT)
2419            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2420            || self
2421                .paths_to_scan
2422                .iter()
2423                .any(|p| p.starts_with(&entry.path))
2424            || self
2425                .path_prefixes_to_scan
2426                .iter()
2427                .any(|p| entry.path.starts_with(p))
2428    }
2429
2430    fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2431        let path = entry.path.clone();
2432        let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2433        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2434        let mut containing_repository = None;
2435        if !ignore_stack.is_abs_path_ignored(&abs_path, true) {
2436            if let Some((workdir_path, repo)) = self.snapshot.local_repo_for_path(&path) {
2437                if let Ok(repo_path) = path.strip_prefix(&workdir_path.0) {
2438                    containing_repository = Some((
2439                        workdir_path,
2440                        repo.repo_ptr.clone(),
2441                        repo.repo_ptr.lock().staged_statuses(repo_path),
2442                    ));
2443                }
2444            }
2445        }
2446        if !ancestor_inodes.contains(&entry.inode) {
2447            ancestor_inodes.insert(entry.inode);
2448            scan_job_tx
2449                .try_send(ScanJob {
2450                    abs_path,
2451                    path,
2452                    ignore_stack,
2453                    scan_queue: scan_job_tx.clone(),
2454                    ancestor_inodes,
2455                    is_external: entry.is_external,
2456                    containing_repository,
2457                })
2458                .unwrap();
2459        }
2460    }
2461
2462    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2463        if let Some(removed_entry_id) = self.removed_entry_ids.remove(&entry.inode) {
2464            entry.id = removed_entry_id;
2465        } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2466            entry.id = existing_entry.id;
2467        }
2468    }
2469
2470    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2471        self.reuse_entry_id(&mut entry);
2472        let entry = self.snapshot.insert_entry(entry, fs);
2473        if entry.path.file_name() == Some(&DOT_GIT) {
2474            self.build_git_repository(entry.path.clone(), fs);
2475        }
2476
2477        #[cfg(test)]
2478        self.snapshot.check_invariants(false);
2479
2480        entry
2481    }
2482
2483    fn populate_dir(
2484        &mut self,
2485        parent_path: &Arc<Path>,
2486        entries: impl IntoIterator<Item = Entry>,
2487        ignore: Option<Arc<Gitignore>>,
2488    ) {
2489        let mut parent_entry = if let Some(parent_entry) = self
2490            .snapshot
2491            .entries_by_path
2492            .get(&PathKey(parent_path.clone()), &())
2493        {
2494            parent_entry.clone()
2495        } else {
2496            log::warn!(
2497                "populating a directory {:?} that has been removed",
2498                parent_path
2499            );
2500            return;
2501        };
2502
2503        match parent_entry.kind {
2504            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2505            EntryKind::Dir => {}
2506            _ => return,
2507        }
2508
2509        if let Some(ignore) = ignore {
2510            let abs_parent_path = self.snapshot.abs_path.join(&parent_path).into();
2511            self.snapshot
2512                .ignores_by_parent_abs_path
2513                .insert(abs_parent_path, (ignore, false));
2514        }
2515
2516        let parent_entry_id = parent_entry.id;
2517        self.scanned_dirs.insert(parent_entry_id);
2518        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2519        let mut entries_by_id_edits = Vec::new();
2520
2521        for entry in entries {
2522            entries_by_id_edits.push(Edit::Insert(PathEntry {
2523                id: entry.id,
2524                path: entry.path.clone(),
2525                is_ignored: entry.is_ignored,
2526                scan_id: self.snapshot.scan_id,
2527            }));
2528            entries_by_path_edits.push(Edit::Insert(entry));
2529        }
2530
2531        self.snapshot
2532            .entries_by_path
2533            .edit(entries_by_path_edits, &());
2534        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2535
2536        if let Err(ix) = self.changed_paths.binary_search(parent_path) {
2537            self.changed_paths.insert(ix, parent_path.clone());
2538        }
2539
2540        #[cfg(test)]
2541        self.snapshot.check_invariants(false);
2542    }
2543
2544    fn remove_path(&mut self, path: &Path) {
2545        let mut new_entries;
2546        let removed_entries;
2547        {
2548            let mut cursor = self.snapshot.entries_by_path.cursor::<TraversalProgress>();
2549            new_entries = cursor.slice(&TraversalTarget::Path(path), Bias::Left, &());
2550            removed_entries = cursor.slice(&TraversalTarget::PathSuccessor(path), Bias::Left, &());
2551            new_entries.append(cursor.suffix(&()), &());
2552        }
2553        self.snapshot.entries_by_path = new_entries;
2554
2555        let mut entries_by_id_edits = Vec::new();
2556        for entry in removed_entries.cursor::<()>() {
2557            let removed_entry_id = self
2558                .removed_entry_ids
2559                .entry(entry.inode)
2560                .or_insert(entry.id);
2561            *removed_entry_id = cmp::max(*removed_entry_id, entry.id);
2562            entries_by_id_edits.push(Edit::Remove(entry.id));
2563        }
2564        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
2565
2566        if path.file_name() == Some(&GITIGNORE) {
2567            let abs_parent_path = self.snapshot.abs_path.join(path.parent().unwrap());
2568            if let Some((_, needs_update)) = self
2569                .snapshot
2570                .ignores_by_parent_abs_path
2571                .get_mut(abs_parent_path.as_path())
2572            {
2573                *needs_update = true;
2574            }
2575        }
2576
2577        #[cfg(test)]
2578        self.snapshot.check_invariants(false);
2579    }
2580
2581    fn reload_repositories(&mut self, dot_git_dirs_to_reload: &HashSet<PathBuf>, fs: &dyn Fs) {
2582        let scan_id = self.snapshot.scan_id;
2583
2584        for dot_git_dir in dot_git_dirs_to_reload {
2585            // If there is already a repository for this .git directory, reload
2586            // the status for all of its files.
2587            let repository = self
2588                .snapshot
2589                .git_repositories
2590                .iter()
2591                .find_map(|(entry_id, repo)| {
2592                    (repo.git_dir_path.as_ref() == dot_git_dir).then(|| (*entry_id, repo.clone()))
2593                });
2594            match repository {
2595                None => {
2596                    self.build_git_repository(Arc::from(dot_git_dir.as_path()), fs);
2597                }
2598                Some((entry_id, repository)) => {
2599                    if repository.git_dir_scan_id == scan_id {
2600                        continue;
2601                    }
2602                    let Some(work_dir) = self
2603                        .snapshot
2604                        .entry_for_id(entry_id)
2605                        .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
2606                    else {
2607                        continue;
2608                    };
2609
2610                    log::info!("reload git repository {dot_git_dir:?}");
2611                    let repository = repository.repo_ptr.lock();
2612                    let branch = repository.branch_name();
2613                    repository.reload_index();
2614
2615                    self.snapshot
2616                        .git_repositories
2617                        .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
2618                    self.snapshot
2619                        .snapshot
2620                        .repository_entries
2621                        .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
2622
2623                    self.update_git_statuses(&work_dir, &*repository);
2624                }
2625            }
2626        }
2627
2628        // Remove any git repositories whose .git entry no longer exists.
2629        let snapshot = &mut self.snapshot;
2630        let mut ids_to_preserve = HashSet::default();
2631        for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
2632            let exists_in_snapshot = snapshot
2633                .entry_for_id(work_directory_id)
2634                .map_or(false, |entry| {
2635                    snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
2636                });
2637            if exists_in_snapshot {
2638                ids_to_preserve.insert(work_directory_id);
2639            } else {
2640                let git_dir_abs_path = snapshot.abs_path().join(&entry.git_dir_path);
2641                let git_dir_excluded = snapshot.is_path_excluded(entry.git_dir_path.to_path_buf());
2642                if git_dir_excluded
2643                    && !matches!(smol::block_on(fs.metadata(&git_dir_abs_path)), Ok(None))
2644                {
2645                    ids_to_preserve.insert(work_directory_id);
2646                }
2647            }
2648        }
2649        snapshot
2650            .git_repositories
2651            .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
2652        snapshot
2653            .repository_entries
2654            .retain(|_, entry| ids_to_preserve.contains(&entry.work_directory.0));
2655    }
2656
2657    fn build_git_repository(
2658        &mut self,
2659        dot_git_path: Arc<Path>,
2660        fs: &dyn Fs,
2661    ) -> Option<(
2662        RepositoryWorkDirectory,
2663        Arc<Mutex<dyn GitRepository>>,
2664        TreeMap<RepoPath, GitFileStatus>,
2665    )> {
2666        log::info!("build git repository {:?}", dot_git_path);
2667
2668        let work_dir_path: Arc<Path> = dot_git_path.parent().unwrap().into();
2669
2670        // Guard against repositories inside the repository metadata
2671        if work_dir_path.iter().any(|component| component == *DOT_GIT) {
2672            return None;
2673        };
2674
2675        let work_dir_id = self
2676            .snapshot
2677            .entry_for_path(work_dir_path.clone())
2678            .map(|entry| entry.id)?;
2679
2680        if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
2681            return None;
2682        }
2683
2684        let abs_path = self.snapshot.abs_path.join(&dot_git_path);
2685        let repository = fs.open_repo(abs_path.as_path())?;
2686        let work_directory = RepositoryWorkDirectory(work_dir_path.clone());
2687
2688        let repo_lock = repository.lock();
2689        self.snapshot.repository_entries.insert(
2690            work_directory.clone(),
2691            RepositoryEntry {
2692                work_directory: work_dir_id.into(),
2693                branch: repo_lock.branch_name().map(Into::into),
2694            },
2695        );
2696
2697        let staged_statuses = self.update_git_statuses(&work_directory, &*repo_lock);
2698        drop(repo_lock);
2699
2700        self.snapshot.git_repositories.insert(
2701            work_dir_id,
2702            LocalRepositoryEntry {
2703                git_dir_scan_id: 0,
2704                repo_ptr: repository.clone(),
2705                git_dir_path: dot_git_path.clone(),
2706            },
2707        );
2708
2709        Some((work_directory, repository, staged_statuses))
2710    }
2711
2712    fn update_git_statuses(
2713        &mut self,
2714        work_directory: &RepositoryWorkDirectory,
2715        repo: &dyn GitRepository,
2716    ) -> TreeMap<RepoPath, GitFileStatus> {
2717        let staged_statuses = repo.staged_statuses(Path::new(""));
2718
2719        let mut changes = vec![];
2720        let mut edits = vec![];
2721
2722        for mut entry in self
2723            .snapshot
2724            .descendent_entries(false, false, &work_directory.0)
2725            .cloned()
2726        {
2727            let Ok(repo_path) = entry.path.strip_prefix(&work_directory.0) else {
2728                continue;
2729            };
2730            let repo_path = RepoPath(repo_path.to_path_buf());
2731            let git_file_status = combine_git_statuses(
2732                staged_statuses.get(&repo_path).copied(),
2733                repo.unstaged_status(&repo_path, entry.mtime),
2734            );
2735            if entry.git_status != git_file_status {
2736                entry.git_status = git_file_status;
2737                changes.push(entry.path.clone());
2738                edits.push(Edit::Insert(entry));
2739            }
2740        }
2741
2742        self.snapshot.entries_by_path.edit(edits, &());
2743        util::extend_sorted(&mut self.changed_paths, changes, usize::MAX, Ord::cmp);
2744        staged_statuses
2745    }
2746}
2747
2748async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2749    let contents = fs.load(abs_path).await?;
2750    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2751    let mut builder = GitignoreBuilder::new(parent);
2752    for line in contents.lines() {
2753        builder.add_line(Some(abs_path.into()), line)?;
2754    }
2755    Ok(builder.build()?)
2756}
2757
2758impl WorktreeId {
2759    pub fn from_usize(handle_id: usize) -> Self {
2760        Self(handle_id)
2761    }
2762
2763    pub fn from_proto(id: u64) -> Self {
2764        Self(id as usize)
2765    }
2766
2767    pub fn to_proto(&self) -> u64 {
2768        self.0 as u64
2769    }
2770
2771    pub fn to_usize(&self) -> usize {
2772        self.0
2773    }
2774}
2775
2776impl fmt::Display for WorktreeId {
2777    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2778        self.0.fmt(f)
2779    }
2780}
2781
2782impl Deref for Worktree {
2783    type Target = Snapshot;
2784
2785    fn deref(&self) -> &Self::Target {
2786        match self {
2787            Worktree::Local(worktree) => &worktree.snapshot,
2788            Worktree::Remote(worktree) => &worktree.snapshot,
2789        }
2790    }
2791}
2792
2793impl Deref for LocalWorktree {
2794    type Target = LocalSnapshot;
2795
2796    fn deref(&self) -> &Self::Target {
2797        &self.snapshot
2798    }
2799}
2800
2801impl Deref for RemoteWorktree {
2802    type Target = Snapshot;
2803
2804    fn deref(&self) -> &Self::Target {
2805        &self.snapshot
2806    }
2807}
2808
2809impl fmt::Debug for LocalWorktree {
2810    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2811        self.snapshot.fmt(f)
2812    }
2813}
2814
2815impl fmt::Debug for Snapshot {
2816    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2817        struct EntriesById<'a>(&'a SumTree<PathEntry>);
2818        struct EntriesByPath<'a>(&'a SumTree<Entry>);
2819
2820        impl<'a> fmt::Debug for EntriesByPath<'a> {
2821            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2822                f.debug_map()
2823                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
2824                    .finish()
2825            }
2826        }
2827
2828        impl<'a> fmt::Debug for EntriesById<'a> {
2829            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2830                f.debug_list().entries(self.0.iter()).finish()
2831            }
2832        }
2833
2834        f.debug_struct("Snapshot")
2835            .field("id", &self.id)
2836            .field("root_name", &self.root_name)
2837            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
2838            .field("entries_by_id", &EntriesById(&self.entries_by_id))
2839            .finish()
2840    }
2841}
2842
2843#[derive(Clone, PartialEq)]
2844pub struct File {
2845    pub worktree: Model<Worktree>,
2846    pub path: Arc<Path>,
2847    pub mtime: SystemTime,
2848    pub entry_id: Option<ProjectEntryId>,
2849    pub is_local: bool,
2850    pub is_deleted: bool,
2851    pub is_private: bool,
2852}
2853
2854impl language::File for File {
2855    fn as_local(&self) -> Option<&dyn language::LocalFile> {
2856        if self.is_local {
2857            Some(self)
2858        } else {
2859            None
2860        }
2861    }
2862
2863    fn mtime(&self) -> SystemTime {
2864        self.mtime
2865    }
2866
2867    fn path(&self) -> &Arc<Path> {
2868        &self.path
2869    }
2870
2871    fn full_path(&self, cx: &AppContext) -> PathBuf {
2872        let mut full_path = PathBuf::new();
2873        let worktree = self.worktree.read(cx);
2874
2875        if worktree.is_visible() {
2876            full_path.push(worktree.root_name());
2877        } else {
2878            let path = worktree.abs_path();
2879
2880            if worktree.is_local() && path.starts_with(HOME.as_path()) {
2881                full_path.push("~");
2882                full_path.push(path.strip_prefix(HOME.as_path()).unwrap());
2883            } else {
2884                full_path.push(path)
2885            }
2886        }
2887
2888        if self.path.components().next().is_some() {
2889            full_path.push(&self.path);
2890        }
2891
2892        full_path
2893    }
2894
2895    /// Returns the last component of this handle's absolute path. If this handle refers to the root
2896    /// of its worktree, then this method will return the name of the worktree itself.
2897    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
2898        self.path
2899            .file_name()
2900            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
2901    }
2902
2903    fn worktree_id(&self) -> usize {
2904        self.worktree.entity_id().as_u64() as usize
2905    }
2906
2907    fn is_deleted(&self) -> bool {
2908        self.is_deleted
2909    }
2910
2911    fn as_any(&self) -> &dyn Any {
2912        self
2913    }
2914
2915    fn to_proto(&self) -> rpc::proto::File {
2916        rpc::proto::File {
2917            worktree_id: self.worktree.entity_id().as_u64(),
2918            entry_id: self.entry_id.map(|id| id.to_proto()),
2919            path: self.path.to_string_lossy().into(),
2920            mtime: Some(self.mtime.into()),
2921            is_deleted: self.is_deleted,
2922        }
2923    }
2924
2925    fn is_private(&self) -> bool {
2926        self.is_private
2927    }
2928}
2929
2930impl language::LocalFile for File {
2931    fn abs_path(&self, cx: &AppContext) -> PathBuf {
2932        let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
2933        if self.path.as_ref() == Path::new("") {
2934            worktree_path.to_path_buf()
2935        } else {
2936            worktree_path.join(&self.path)
2937        }
2938    }
2939
2940    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
2941        let worktree = self.worktree.read(cx).as_local().unwrap();
2942        let abs_path = worktree.absolutize(&self.path);
2943        let fs = worktree.fs.clone();
2944        cx.background_executor()
2945            .spawn(async move { fs.load(&abs_path?).await })
2946    }
2947
2948    fn buffer_reloaded(
2949        &self,
2950        buffer_id: BufferId,
2951        version: &clock::Global,
2952        fingerprint: RopeFingerprint,
2953        line_ending: LineEnding,
2954        mtime: SystemTime,
2955        cx: &mut AppContext,
2956    ) {
2957        let worktree = self.worktree.read(cx).as_local().unwrap();
2958        if let Some(project_id) = worktree.share.as_ref().map(|share| share.project_id) {
2959            worktree
2960                .client
2961                .send(proto::BufferReloaded {
2962                    project_id,
2963                    buffer_id: buffer_id.into(),
2964                    version: serialize_version(version),
2965                    mtime: Some(mtime.into()),
2966                    fingerprint: serialize_fingerprint(fingerprint),
2967                    line_ending: serialize_line_ending(line_ending) as i32,
2968                })
2969                .log_err();
2970        }
2971    }
2972}
2973
2974impl File {
2975    pub fn for_entry(entry: Entry, worktree: Model<Worktree>) -> Arc<Self> {
2976        Arc::new(Self {
2977            worktree,
2978            path: entry.path.clone(),
2979            mtime: entry.mtime,
2980            entry_id: Some(entry.id),
2981            is_local: true,
2982            is_deleted: false,
2983            is_private: entry.is_private,
2984        })
2985    }
2986
2987    pub fn from_proto(
2988        proto: rpc::proto::File,
2989        worktree: Model<Worktree>,
2990        cx: &AppContext,
2991    ) -> Result<Self> {
2992        let worktree_id = worktree
2993            .read(cx)
2994            .as_remote()
2995            .ok_or_else(|| anyhow!("not remote"))?
2996            .id();
2997
2998        if worktree_id.to_proto() != proto.worktree_id {
2999            return Err(anyhow!("worktree id does not match file"));
3000        }
3001
3002        Ok(Self {
3003            worktree,
3004            path: Path::new(&proto.path).into(),
3005            mtime: proto.mtime.ok_or_else(|| anyhow!("no timestamp"))?.into(),
3006            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3007            is_local: false,
3008            is_deleted: proto.is_deleted,
3009            is_private: false,
3010        })
3011    }
3012
3013    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3014        file.and_then(|f| f.as_any().downcast_ref())
3015    }
3016
3017    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
3018        self.worktree.read(cx).id()
3019    }
3020
3021    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
3022        if self.is_deleted {
3023            None
3024        } else {
3025            self.entry_id
3026        }
3027    }
3028}
3029
3030#[derive(Clone, Debug, PartialEq, Eq)]
3031pub struct Entry {
3032    pub id: ProjectEntryId,
3033    pub kind: EntryKind,
3034    pub path: Arc<Path>,
3035    pub inode: u64,
3036    pub mtime: SystemTime,
3037    pub is_symlink: bool,
3038
3039    /// Whether this entry is ignored by Git.
3040    ///
3041    /// We only scan ignored entries once the directory is expanded and
3042    /// exclude them from searches.
3043    pub is_ignored: bool,
3044
3045    /// Whether this entry's canonical path is outside of the worktree.
3046    /// This means the entry is only accessible from the worktree root via a
3047    /// symlink.
3048    ///
3049    /// We only scan entries outside of the worktree once the symlinked
3050    /// directory is expanded. External entries are treated like gitignored
3051    /// entries in that they are not included in searches.
3052    pub is_external: bool,
3053    pub git_status: Option<GitFileStatus>,
3054    /// Whether this entry is considered to be a `.env` file.
3055    pub is_private: bool,
3056}
3057
3058#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3059pub enum EntryKind {
3060    UnloadedDir,
3061    PendingDir,
3062    Dir,
3063    File(CharBag),
3064}
3065
3066#[derive(Clone, Copy, Debug, PartialEq)]
3067pub enum PathChange {
3068    /// A filesystem entry was was created.
3069    Added,
3070    /// A filesystem entry was removed.
3071    Removed,
3072    /// A filesystem entry was updated.
3073    Updated,
3074    /// A filesystem entry was either updated or added. We don't know
3075    /// whether or not it already existed, because the path had not
3076    /// been loaded before the event.
3077    AddedOrUpdated,
3078    /// A filesystem entry was found during the initial scan of the worktree.
3079    Loaded,
3080}
3081
3082pub struct GitRepositoryChange {
3083    /// The previous state of the repository, if it already existed.
3084    pub old_repository: Option<RepositoryEntry>,
3085}
3086
3087pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
3088pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
3089
3090impl Entry {
3091    fn new(
3092        path: Arc<Path>,
3093        metadata: &fs::Metadata,
3094        next_entry_id: &AtomicUsize,
3095        root_char_bag: CharBag,
3096    ) -> Self {
3097        Self {
3098            id: ProjectEntryId::new(next_entry_id),
3099            kind: if metadata.is_dir {
3100                EntryKind::PendingDir
3101            } else {
3102                EntryKind::File(char_bag_for_path(root_char_bag, &path))
3103            },
3104            path,
3105            inode: metadata.inode,
3106            mtime: metadata.mtime,
3107            is_symlink: metadata.is_symlink,
3108            is_ignored: false,
3109            is_external: false,
3110            is_private: false,
3111            git_status: None,
3112        }
3113    }
3114
3115    pub fn is_dir(&self) -> bool {
3116        self.kind.is_dir()
3117    }
3118
3119    pub fn is_file(&self) -> bool {
3120        self.kind.is_file()
3121    }
3122
3123    pub fn git_status(&self) -> Option<GitFileStatus> {
3124        self.git_status
3125    }
3126}
3127
3128impl EntryKind {
3129    pub fn is_dir(&self) -> bool {
3130        matches!(
3131            self,
3132            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3133        )
3134    }
3135
3136    pub fn is_unloaded(&self) -> bool {
3137        matches!(self, EntryKind::UnloadedDir)
3138    }
3139
3140    pub fn is_file(&self) -> bool {
3141        matches!(self, EntryKind::File(_))
3142    }
3143}
3144
3145impl sum_tree::Item for Entry {
3146    type Summary = EntrySummary;
3147
3148    fn summary(&self) -> Self::Summary {
3149        let non_ignored_count = if self.is_ignored || self.is_external {
3150            0
3151        } else {
3152            1
3153        };
3154        let file_count;
3155        let non_ignored_file_count;
3156        if self.is_file() {
3157            file_count = 1;
3158            non_ignored_file_count = non_ignored_count;
3159        } else {
3160            file_count = 0;
3161            non_ignored_file_count = 0;
3162        }
3163
3164        let mut statuses = GitStatuses::default();
3165        match self.git_status {
3166            Some(status) => match status {
3167                GitFileStatus::Added => statuses.added = 1,
3168                GitFileStatus::Modified => statuses.modified = 1,
3169                GitFileStatus::Conflict => statuses.conflict = 1,
3170            },
3171            None => {}
3172        }
3173
3174        EntrySummary {
3175            max_path: self.path.clone(),
3176            count: 1,
3177            non_ignored_count,
3178            file_count,
3179            non_ignored_file_count,
3180            statuses,
3181        }
3182    }
3183}
3184
3185impl sum_tree::KeyedItem for Entry {
3186    type Key = PathKey;
3187
3188    fn key(&self) -> Self::Key {
3189        PathKey(self.path.clone())
3190    }
3191}
3192
3193#[derive(Clone, Debug)]
3194pub struct EntrySummary {
3195    max_path: Arc<Path>,
3196    count: usize,
3197    non_ignored_count: usize,
3198    file_count: usize,
3199    non_ignored_file_count: usize,
3200    statuses: GitStatuses,
3201}
3202
3203impl Default for EntrySummary {
3204    fn default() -> Self {
3205        Self {
3206            max_path: Arc::from(Path::new("")),
3207            count: 0,
3208            non_ignored_count: 0,
3209            file_count: 0,
3210            non_ignored_file_count: 0,
3211            statuses: Default::default(),
3212        }
3213    }
3214}
3215
3216impl sum_tree::Summary for EntrySummary {
3217    type Context = ();
3218
3219    fn add_summary(&mut self, rhs: &Self, _: &()) {
3220        self.max_path = rhs.max_path.clone();
3221        self.count += rhs.count;
3222        self.non_ignored_count += rhs.non_ignored_count;
3223        self.file_count += rhs.file_count;
3224        self.non_ignored_file_count += rhs.non_ignored_file_count;
3225        self.statuses += rhs.statuses;
3226    }
3227}
3228
3229#[derive(Clone, Debug)]
3230struct PathEntry {
3231    id: ProjectEntryId,
3232    path: Arc<Path>,
3233    is_ignored: bool,
3234    scan_id: usize,
3235}
3236
3237impl sum_tree::Item for PathEntry {
3238    type Summary = PathEntrySummary;
3239
3240    fn summary(&self) -> Self::Summary {
3241        PathEntrySummary { max_id: self.id }
3242    }
3243}
3244
3245impl sum_tree::KeyedItem for PathEntry {
3246    type Key = ProjectEntryId;
3247
3248    fn key(&self) -> Self::Key {
3249        self.id
3250    }
3251}
3252
3253#[derive(Clone, Debug, Default)]
3254struct PathEntrySummary {
3255    max_id: ProjectEntryId,
3256}
3257
3258impl sum_tree::Summary for PathEntrySummary {
3259    type Context = ();
3260
3261    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3262        self.max_id = summary.max_id;
3263    }
3264}
3265
3266impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3267    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3268        *self = summary.max_id;
3269    }
3270}
3271
3272#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3273pub struct PathKey(Arc<Path>);
3274
3275impl Default for PathKey {
3276    fn default() -> Self {
3277        Self(Path::new("").into())
3278    }
3279}
3280
3281impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3282    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3283        self.0 = summary.max_path.clone();
3284    }
3285}
3286
3287struct BackgroundScanner {
3288    state: Mutex<BackgroundScannerState>,
3289    fs: Arc<dyn Fs>,
3290    fs_case_sensitive: bool,
3291    status_updates_tx: UnboundedSender<ScanState>,
3292    executor: BackgroundExecutor,
3293    scan_requests_rx: channel::Receiver<ScanRequest>,
3294    path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3295    next_entry_id: Arc<AtomicUsize>,
3296    phase: BackgroundScannerPhase,
3297}
3298
3299#[derive(PartialEq)]
3300enum BackgroundScannerPhase {
3301    InitialScan,
3302    EventsReceivedDuringInitialScan,
3303    Events,
3304}
3305
3306impl BackgroundScanner {
3307    #[allow(clippy::too_many_arguments)]
3308    fn new(
3309        snapshot: LocalSnapshot,
3310        next_entry_id: Arc<AtomicUsize>,
3311        fs: Arc<dyn Fs>,
3312        fs_case_sensitive: bool,
3313        status_updates_tx: UnboundedSender<ScanState>,
3314        executor: BackgroundExecutor,
3315        scan_requests_rx: channel::Receiver<ScanRequest>,
3316        path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3317    ) -> Self {
3318        Self {
3319            fs,
3320            fs_case_sensitive,
3321            status_updates_tx,
3322            executor,
3323            scan_requests_rx,
3324            path_prefixes_to_scan_rx,
3325            next_entry_id,
3326            state: Mutex::new(BackgroundScannerState {
3327                prev_snapshot: snapshot.snapshot.clone(),
3328                snapshot,
3329                scanned_dirs: Default::default(),
3330                path_prefixes_to_scan: Default::default(),
3331                paths_to_scan: Default::default(),
3332                removed_entry_ids: Default::default(),
3333                changed_paths: Default::default(),
3334            }),
3335            phase: BackgroundScannerPhase::InitialScan,
3336        }
3337    }
3338
3339    async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<fs::Event>>>>) {
3340        use futures::FutureExt as _;
3341
3342        // Populate ignores above the root.
3343        let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3344        for (index, ancestor) in root_abs_path.ancestors().enumerate() {
3345            if index != 0 {
3346                if let Ok(ignore) =
3347                    build_gitignore(&ancestor.join(&*GITIGNORE), self.fs.as_ref()).await
3348                {
3349                    self.state
3350                        .lock()
3351                        .snapshot
3352                        .ignores_by_parent_abs_path
3353                        .insert(ancestor.into(), (ignore.into(), false));
3354                }
3355            }
3356            if ancestor.join(&*DOT_GIT).is_dir() {
3357                // Reached root of git repository.
3358                break;
3359            }
3360        }
3361
3362        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3363        {
3364            let mut state = self.state.lock();
3365            state.snapshot.scan_id += 1;
3366            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3367                let ignore_stack = state
3368                    .snapshot
3369                    .ignore_stack_for_abs_path(&root_abs_path, true);
3370                if ignore_stack.is_abs_path_ignored(&root_abs_path, true) {
3371                    root_entry.is_ignored = true;
3372                    state.insert_entry(root_entry.clone(), self.fs.as_ref());
3373                }
3374                state.enqueue_scan_dir(root_abs_path, &root_entry, &scan_job_tx);
3375            }
3376        };
3377
3378        // Perform an initial scan of the directory.
3379        drop(scan_job_tx);
3380        self.scan_dirs(true, scan_job_rx).await;
3381        {
3382            let mut state = self.state.lock();
3383            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3384        }
3385
3386        self.send_status_update(false, None);
3387
3388        // Process any any FS events that occurred while performing the initial scan.
3389        // For these events, update events cannot be as precise, because we didn't
3390        // have the previous state loaded yet.
3391        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3392        if let Poll::Ready(Some(events)) = futures::poll!(fs_events_rx.next()) {
3393            let mut paths = fs::fs_events_paths(events);
3394
3395            while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3396                paths.extend(fs::fs_events_paths(more_events));
3397            }
3398            self.process_events(paths).await;
3399        }
3400
3401        // Continue processing events until the worktree is dropped.
3402        self.phase = BackgroundScannerPhase::Events;
3403        loop {
3404            select_biased! {
3405                // Process any path refresh requests from the worktree. Prioritize
3406                // these before handling changes reported by the filesystem.
3407                request = self.scan_requests_rx.recv().fuse() => {
3408                    let Ok(request) = request else { break };
3409                    if !self.process_scan_request(request, false).await {
3410                        return;
3411                    }
3412                }
3413
3414                path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
3415                    let Ok(path_prefix) = path_prefix else { break };
3416                    log::trace!("adding path prefix {:?}", path_prefix);
3417
3418                    let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
3419                    if did_scan {
3420                        let abs_path =
3421                        {
3422                            let mut state = self.state.lock();
3423                            state.path_prefixes_to_scan.insert(path_prefix.clone());
3424                            state.snapshot.abs_path.join(&path_prefix)
3425                        };
3426
3427                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3428                            self.process_events(vec![abs_path]).await;
3429                        }
3430                    }
3431                }
3432
3433                events = fs_events_rx.next().fuse() => {
3434                    let Some(events) = events else { break };
3435                    let mut paths = fs::fs_events_paths(events);
3436
3437                    while let Poll::Ready(Some(more_events)) = futures::poll!(fs_events_rx.next()) {
3438                        paths.extend(fs::fs_events_paths(more_events));
3439                    }
3440                    self.process_events(paths.clone()).await;
3441                }
3442            }
3443        }
3444    }
3445
3446    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3447        log::debug!("rescanning paths {:?}", request.relative_paths);
3448
3449        request.relative_paths.sort_unstable();
3450        self.forcibly_load_paths(&request.relative_paths).await;
3451
3452        let root_path = self.state.lock().snapshot.abs_path.clone();
3453        let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3454            Ok(path) => path,
3455            Err(err) => {
3456                log::error!("failed to canonicalize root path: {}", err);
3457                return false;
3458            }
3459        };
3460        let abs_paths = request
3461            .relative_paths
3462            .iter()
3463            .map(|path| {
3464                if path.file_name().is_some() {
3465                    root_canonical_path.join(path)
3466                } else {
3467                    root_canonical_path.clone()
3468                }
3469            })
3470            .collect::<Vec<_>>();
3471
3472        self.reload_entries_for_paths(
3473            root_path,
3474            root_canonical_path,
3475            &request.relative_paths,
3476            abs_paths,
3477            None,
3478        )
3479        .await;
3480        self.send_status_update(scanning, Some(request.done))
3481    }
3482
3483    async fn process_events(&mut self, mut abs_paths: Vec<PathBuf>) {
3484        let root_path = self.state.lock().snapshot.abs_path.clone();
3485        let root_canonical_path = match self.fs.canonicalize(&root_path).await {
3486            Ok(path) => path,
3487            Err(err) => {
3488                log::error!("failed to canonicalize root path: {}", err);
3489                return;
3490            }
3491        };
3492
3493        let mut relative_paths = Vec::with_capacity(abs_paths.len());
3494        let mut dot_git_paths_to_reload = HashSet::default();
3495        abs_paths.sort_unstable();
3496        abs_paths.dedup_by(|a, b| a.starts_with(&b));
3497        abs_paths.retain(|abs_path| {
3498            let snapshot = &self.state.lock().snapshot;
3499            {
3500                let mut is_git_related = false;
3501                if let Some(dot_git_dir) = abs_path
3502                    .ancestors()
3503                    .find(|ancestor| ancestor.file_name() == Some(*DOT_GIT))
3504                {
3505                    let dot_git_path = dot_git_dir
3506                        .strip_prefix(&root_canonical_path)
3507                        .ok()
3508                        .map(|path| path.to_path_buf())
3509                        .unwrap_or_else(|| dot_git_dir.to_path_buf());
3510                    dot_git_paths_to_reload.insert(dot_git_path.to_path_buf());
3511                    is_git_related = true;
3512                }
3513
3514                let relative_path: Arc<Path> =
3515                    if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
3516                        path.into()
3517                    } else {
3518                        log::error!(
3519                        "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3520                    );
3521                        return false;
3522                    };
3523
3524                let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
3525                    snapshot
3526                        .entry_for_path(parent)
3527                        .map_or(false, |entry| entry.kind == EntryKind::Dir)
3528                });
3529                if !parent_dir_is_loaded {
3530                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
3531                    return false;
3532                }
3533
3534                if snapshot.is_path_excluded(relative_path.to_path_buf()) {
3535                    if !is_git_related {
3536                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
3537                    }
3538                    return false;
3539                }
3540
3541                relative_paths.push(relative_path);
3542                true
3543            }
3544        });
3545
3546        if dot_git_paths_to_reload.is_empty() && relative_paths.is_empty() {
3547            return;
3548        }
3549
3550        if !relative_paths.is_empty() {
3551            log::debug!("received fs events {:?}", relative_paths);
3552
3553            let (scan_job_tx, scan_job_rx) = channel::unbounded();
3554            self.reload_entries_for_paths(
3555                root_path,
3556                root_canonical_path,
3557                &relative_paths,
3558                abs_paths,
3559                Some(scan_job_tx.clone()),
3560            )
3561            .await;
3562            drop(scan_job_tx);
3563            self.scan_dirs(false, scan_job_rx).await;
3564
3565            let (scan_job_tx, scan_job_rx) = channel::unbounded();
3566            self.update_ignore_statuses(scan_job_tx).await;
3567            self.scan_dirs(false, scan_job_rx).await;
3568        }
3569
3570        {
3571            let mut state = self.state.lock();
3572            if !dot_git_paths_to_reload.is_empty() {
3573                if relative_paths.is_empty() {
3574                    state.snapshot.scan_id += 1;
3575                }
3576                log::debug!("reloading repositories: {dot_git_paths_to_reload:?}");
3577                state.reload_repositories(&dot_git_paths_to_reload, self.fs.as_ref());
3578            }
3579            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3580            for (_, entry_id) in mem::take(&mut state.removed_entry_ids) {
3581                state.scanned_dirs.remove(&entry_id);
3582            }
3583        }
3584
3585        self.send_status_update(false, None);
3586    }
3587
3588    async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
3589        let (scan_job_tx, mut scan_job_rx) = channel::unbounded();
3590        {
3591            let mut state = self.state.lock();
3592            let root_path = state.snapshot.abs_path.clone();
3593            for path in paths {
3594                for ancestor in path.ancestors() {
3595                    if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
3596                        if entry.kind == EntryKind::UnloadedDir {
3597                            let abs_path = root_path.join(ancestor);
3598                            state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
3599                            state.paths_to_scan.insert(path.clone());
3600                            break;
3601                        }
3602                    }
3603                }
3604            }
3605            drop(scan_job_tx);
3606        }
3607        while let Some(job) = scan_job_rx.next().await {
3608            self.scan_dir(&job).await.log_err();
3609        }
3610
3611        mem::take(&mut self.state.lock().paths_to_scan).len() > 0
3612    }
3613
3614    async fn scan_dirs(
3615        &self,
3616        enable_progress_updates: bool,
3617        scan_jobs_rx: channel::Receiver<ScanJob>,
3618    ) {
3619        use futures::FutureExt as _;
3620
3621        if self
3622            .status_updates_tx
3623            .unbounded_send(ScanState::Started)
3624            .is_err()
3625        {
3626            return;
3627        }
3628
3629        let progress_update_count = AtomicUsize::new(0);
3630        self.executor
3631            .scoped(|scope| {
3632                for _ in 0..self.executor.num_cpus() {
3633                    scope.spawn(async {
3634                        let mut last_progress_update_count = 0;
3635                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
3636                        futures::pin_mut!(progress_update_timer);
3637
3638                        loop {
3639                            select_biased! {
3640                                // Process any path refresh requests before moving on to process
3641                                // the scan queue, so that user operations are prioritized.
3642                                request = self.scan_requests_rx.recv().fuse() => {
3643                                    let Ok(request) = request else { break };
3644                                    if !self.process_scan_request(request, true).await {
3645                                        return;
3646                                    }
3647                                }
3648
3649                                // Send periodic progress updates to the worktree. Use an atomic counter
3650                                // to ensure that only one of the workers sends a progress update after
3651                                // the update interval elapses.
3652                                _ = progress_update_timer => {
3653                                    match progress_update_count.compare_exchange(
3654                                        last_progress_update_count,
3655                                        last_progress_update_count + 1,
3656                                        SeqCst,
3657                                        SeqCst
3658                                    ) {
3659                                        Ok(_) => {
3660                                            last_progress_update_count += 1;
3661                                            self.send_status_update(true, None);
3662                                        }
3663                                        Err(count) => {
3664                                            last_progress_update_count = count;
3665                                        }
3666                                    }
3667                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
3668                                }
3669
3670                                // Recursively load directories from the file system.
3671                                job = scan_jobs_rx.recv().fuse() => {
3672                                    let Ok(job) = job else { break };
3673                                    if let Err(err) = self.scan_dir(&job).await {
3674                                        if job.path.as_ref() != Path::new("") {
3675                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
3676                                        }
3677                                    }
3678                                }
3679                            }
3680                        }
3681                    })
3682                }
3683            })
3684            .await;
3685    }
3686
3687    fn send_status_update(&self, scanning: bool, barrier: Option<barrier::Sender>) -> bool {
3688        let mut state = self.state.lock();
3689        if state.changed_paths.is_empty() && scanning {
3690            return true;
3691        }
3692
3693        let new_snapshot = state.snapshot.clone();
3694        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
3695        let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
3696        state.changed_paths.clear();
3697
3698        self.status_updates_tx
3699            .unbounded_send(ScanState::Updated {
3700                snapshot: new_snapshot,
3701                changes,
3702                scanning,
3703                barrier,
3704            })
3705            .is_ok()
3706    }
3707
3708    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
3709        let root_abs_path;
3710        let mut ignore_stack;
3711        let mut new_ignore;
3712        let root_char_bag;
3713        let next_entry_id;
3714        {
3715            let state = self.state.lock();
3716            let snapshot = &state.snapshot;
3717            root_abs_path = snapshot.abs_path().clone();
3718            if snapshot.is_path_excluded(job.path.to_path_buf()) {
3719                log::error!("skipping excluded directory {:?}", job.path);
3720                return Ok(());
3721            }
3722            log::debug!("scanning directory {:?}", job.path);
3723            ignore_stack = job.ignore_stack.clone();
3724            new_ignore = None;
3725            root_char_bag = snapshot.root_char_bag;
3726            next_entry_id = self.next_entry_id.clone();
3727            drop(state);
3728        }
3729
3730        let mut dotgit_path = None;
3731        let mut root_canonical_path = None;
3732        let mut new_entries: Vec<Entry> = Vec::new();
3733        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
3734        let mut child_paths = self.fs.read_dir(&job.abs_path).await?;
3735        while let Some(child_abs_path) = child_paths.next().await {
3736            let child_abs_path: Arc<Path> = match child_abs_path {
3737                Ok(child_abs_path) => child_abs_path.into(),
3738                Err(error) => {
3739                    log::error!("error processing entry {:?}", error);
3740                    continue;
3741                }
3742            };
3743            let child_name = child_abs_path.file_name().unwrap();
3744            let child_path: Arc<Path> = job.path.join(child_name).into();
3745            // If we find a .gitignore, add it to the stack of ignores used to determine which paths are ignored
3746            if child_name == *GITIGNORE {
3747                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3748                    Ok(ignore) => {
3749                        let ignore = Arc::new(ignore);
3750                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3751                        new_ignore = Some(ignore);
3752                    }
3753                    Err(error) => {
3754                        log::error!(
3755                            "error loading .gitignore file {:?} - {:?}",
3756                            child_name,
3757                            error
3758                        );
3759                    }
3760                }
3761
3762                // Update ignore status of any child entries we've already processed to reflect the
3763                // ignore file in the current directory. Because `.gitignore` starts with a `.`,
3764                // there should rarely be too numerous. Update the ignore stack associated with any
3765                // new jobs as well.
3766                let mut new_jobs = new_jobs.iter_mut();
3767                for entry in &mut new_entries {
3768                    let entry_abs_path = root_abs_path.join(&entry.path);
3769                    entry.is_ignored =
3770                        ignore_stack.is_abs_path_ignored(&entry_abs_path, entry.is_dir());
3771
3772                    if entry.is_dir() {
3773                        if let Some(job) = new_jobs.next().expect("missing scan job for entry") {
3774                            job.ignore_stack = if entry.is_ignored {
3775                                IgnoreStack::all()
3776                            } else {
3777                                ignore_stack.clone()
3778                            };
3779                        }
3780                    }
3781                }
3782            }
3783            // If we find a .git, we'll need to load the repository.
3784            else if child_name == *DOT_GIT {
3785                dotgit_path = Some(child_path.clone());
3786            }
3787
3788            {
3789                let relative_path = job.path.join(child_name);
3790                let mut state = self.state.lock();
3791                if state.snapshot.is_path_excluded(relative_path.clone()) {
3792                    log::debug!("skipping excluded child entry {relative_path:?}");
3793                    state.remove_path(&relative_path);
3794                    continue;
3795                }
3796                drop(state);
3797            }
3798
3799            let child_metadata = match self.fs.metadata(&child_abs_path).await {
3800                Ok(Some(metadata)) => metadata,
3801                Ok(None) => continue,
3802                Err(err) => {
3803                    log::error!("error processing {child_abs_path:?}: {err:?}");
3804                    continue;
3805                }
3806            };
3807
3808            let mut child_entry = Entry::new(
3809                child_path.clone(),
3810                &child_metadata,
3811                &next_entry_id,
3812                root_char_bag,
3813            );
3814
3815            if job.is_external {
3816                child_entry.is_external = true;
3817            } else if child_metadata.is_symlink {
3818                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
3819                    Ok(path) => path,
3820                    Err(err) => {
3821                        log::error!(
3822                            "error reading target of symlink {:?}: {:?}",
3823                            child_abs_path,
3824                            err
3825                        );
3826                        continue;
3827                    }
3828                };
3829
3830                // lazily canonicalize the root path in order to determine if
3831                // symlinks point outside of the worktree.
3832                let root_canonical_path = match &root_canonical_path {
3833                    Some(path) => path,
3834                    None => match self.fs.canonicalize(&root_abs_path).await {
3835                        Ok(path) => root_canonical_path.insert(path),
3836                        Err(err) => {
3837                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
3838                            continue;
3839                        }
3840                    },
3841                };
3842
3843                if !canonical_path.starts_with(root_canonical_path) {
3844                    child_entry.is_external = true;
3845                }
3846            }
3847
3848            if child_entry.is_dir() {
3849                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3850
3851                // Avoid recursing until crash in the case of a recursive symlink
3852                if !job.ancestor_inodes.contains(&child_entry.inode) {
3853                    let mut ancestor_inodes = job.ancestor_inodes.clone();
3854                    ancestor_inodes.insert(child_entry.inode);
3855
3856                    new_jobs.push(Some(ScanJob {
3857                        abs_path: child_abs_path.clone(),
3858                        path: child_path,
3859                        is_external: child_entry.is_external,
3860                        ignore_stack: if child_entry.is_ignored {
3861                            IgnoreStack::all()
3862                        } else {
3863                            ignore_stack.clone()
3864                        },
3865                        ancestor_inodes,
3866                        scan_queue: job.scan_queue.clone(),
3867                        containing_repository: job.containing_repository.clone(),
3868                    }));
3869                } else {
3870                    new_jobs.push(None);
3871                }
3872            } else {
3873                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3874                if !child_entry.is_ignored {
3875                    if let Some((repository_dir, repository, staged_statuses)) =
3876                        &job.containing_repository
3877                    {
3878                        if let Ok(repo_path) = child_entry.path.strip_prefix(&repository_dir.0) {
3879                            let repo_path = RepoPath(repo_path.into());
3880                            child_entry.git_status = combine_git_statuses(
3881                                staged_statuses.get(&repo_path).copied(),
3882                                repository
3883                                    .lock()
3884                                    .unstaged_status(&repo_path, child_entry.mtime),
3885                            );
3886                        }
3887                    }
3888                }
3889            }
3890
3891            {
3892                let relative_path = job.path.join(child_name);
3893                let state = self.state.lock();
3894                if state.snapshot.is_path_private(&relative_path) {
3895                    log::debug!("detected private file: {relative_path:?}");
3896                    child_entry.is_private = true;
3897                }
3898                drop(state)
3899            }
3900
3901            new_entries.push(child_entry);
3902        }
3903
3904        let mut state = self.state.lock();
3905
3906        // Identify any subdirectories that should not be scanned.
3907        let mut job_ix = 0;
3908        for entry in &mut new_entries {
3909            state.reuse_entry_id(entry);
3910            if entry.is_dir() {
3911                if state.should_scan_directory(entry) {
3912                    job_ix += 1;
3913                } else {
3914                    log::debug!("defer scanning directory {:?}", entry.path);
3915                    entry.kind = EntryKind::UnloadedDir;
3916                    new_jobs.remove(job_ix);
3917                }
3918            }
3919        }
3920
3921        state.populate_dir(&job.path, new_entries, new_ignore);
3922
3923        let repository =
3924            dotgit_path.and_then(|path| state.build_git_repository(path, self.fs.as_ref()));
3925
3926        for mut new_job in new_jobs.into_iter().flatten() {
3927            if let Some(containing_repository) = &repository {
3928                new_job.containing_repository = Some(containing_repository.clone());
3929            }
3930
3931            job.scan_queue
3932                .try_send(new_job)
3933                .expect("channel is unbounded");
3934        }
3935
3936        Ok(())
3937    }
3938
3939    async fn reload_entries_for_paths(
3940        &self,
3941        root_abs_path: Arc<Path>,
3942        root_canonical_path: PathBuf,
3943        relative_paths: &[Arc<Path>],
3944        abs_paths: Vec<PathBuf>,
3945        scan_queue_tx: Option<Sender<ScanJob>>,
3946    ) {
3947        let metadata = futures::future::join_all(
3948            abs_paths
3949                .iter()
3950                .map(|abs_path| async move {
3951                    let metadata = self.fs.metadata(abs_path).await?;
3952                    if let Some(metadata) = metadata {
3953                        let canonical_path = self.fs.canonicalize(abs_path).await?;
3954
3955                        // If we're on a case-insensitive filesystem (default on macOS), we want
3956                        // to only ignore metadata for non-symlink files if their absolute-path matches
3957                        // the canonical-path.
3958                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
3959                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
3960                        // treated as removed.
3961                        if !self.fs_case_sensitive && !metadata.is_symlink {
3962                            let canonical_file_name = canonical_path.file_name();
3963                            let file_name = abs_path.file_name();
3964                            if canonical_file_name != file_name {
3965                                return Ok(None);
3966                            }
3967                        }
3968
3969                        anyhow::Ok(Some((metadata, canonical_path)))
3970                    } else {
3971                        Ok(None)
3972                    }
3973                })
3974                .collect::<Vec<_>>(),
3975        )
3976        .await;
3977
3978        let mut state = self.state.lock();
3979        let snapshot = &mut state.snapshot;
3980        let is_idle = snapshot.completed_scan_id == snapshot.scan_id;
3981        let doing_recursive_update = scan_queue_tx.is_some();
3982        snapshot.scan_id += 1;
3983        if is_idle && !doing_recursive_update {
3984            snapshot.completed_scan_id = snapshot.scan_id;
3985        }
3986
3987        // Remove any entries for paths that no longer exist or are being recursively
3988        // refreshed. Do this before adding any new entries, so that renames can be
3989        // detected regardless of the order of the paths.
3990        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3991            if matches!(metadata, Ok(None)) || doing_recursive_update {
3992                log::trace!("remove path {:?}", path);
3993                state.remove_path(path);
3994            }
3995        }
3996
3997        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
3998            let abs_path: Arc<Path> = root_abs_path.join(&path).into();
3999            match metadata {
4000                Ok(Some((metadata, canonical_path))) => {
4001                    let ignore_stack = state
4002                        .snapshot
4003                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
4004
4005                    let mut fs_entry = Entry::new(
4006                        path.clone(),
4007                        metadata,
4008                        self.next_entry_id.as_ref(),
4009                        state.snapshot.root_char_bag,
4010                    );
4011                    let is_dir = fs_entry.is_dir();
4012                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4013                    fs_entry.is_external = !canonical_path.starts_with(&root_canonical_path);
4014                    fs_entry.is_private = state.snapshot.is_path_private(path);
4015
4016                    if !is_dir && !fs_entry.is_ignored && !fs_entry.is_external {
4017                        if let Some((work_dir, repo)) = state.snapshot.local_repo_for_path(path) {
4018                            if let Ok(repo_path) = path.strip_prefix(work_dir.0) {
4019                                let repo_path = RepoPath(repo_path.into());
4020                                let repo = repo.repo_ptr.lock();
4021                                fs_entry.git_status = repo.status(&repo_path, fs_entry.mtime);
4022                            }
4023                        }
4024                    }
4025
4026                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, fs_entry.is_dir()) {
4027                        if state.should_scan_directory(&fs_entry) {
4028                            state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
4029                        } else {
4030                            fs_entry.kind = EntryKind::UnloadedDir;
4031                        }
4032                    }
4033
4034                    state.insert_entry(fs_entry, self.fs.as_ref());
4035                }
4036                Ok(None) => {
4037                    self.remove_repo_path(path, &mut state.snapshot);
4038                }
4039                Err(err) => {
4040                    // TODO - create a special 'error' entry in the entries tree to mark this
4041                    log::error!("error reading file {abs_path:?} on event: {err:#}");
4042                }
4043            }
4044        }
4045
4046        util::extend_sorted(
4047            &mut state.changed_paths,
4048            relative_paths.iter().cloned(),
4049            usize::MAX,
4050            Ord::cmp,
4051        );
4052    }
4053
4054    fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
4055        if !path
4056            .components()
4057            .any(|component| component.as_os_str() == *DOT_GIT)
4058        {
4059            if let Some(repository) = snapshot.repository_for_work_directory(path) {
4060                let entry = repository.work_directory.0;
4061                snapshot.git_repositories.remove(&entry);
4062                snapshot
4063                    .snapshot
4064                    .repository_entries
4065                    .remove(&RepositoryWorkDirectory(path.into()));
4066                return Some(());
4067            }
4068        }
4069
4070        // TODO statuses
4071        // Track when a .git is removed and iterate over the file system there
4072
4073        Some(())
4074    }
4075
4076    async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
4077        use futures::FutureExt as _;
4078
4079        let mut snapshot = self.state.lock().snapshot.clone();
4080        let mut ignores_to_update = Vec::new();
4081        let mut ignores_to_delete = Vec::new();
4082        let abs_path = snapshot.abs_path.clone();
4083        for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
4084            if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
4085                if *needs_update {
4086                    *needs_update = false;
4087                    if snapshot.snapshot.entry_for_path(parent_path).is_some() {
4088                        ignores_to_update.push(parent_abs_path.clone());
4089                    }
4090                }
4091
4092                let ignore_path = parent_path.join(&*GITIGNORE);
4093                if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
4094                    ignores_to_delete.push(parent_abs_path.clone());
4095                }
4096            }
4097        }
4098
4099        for parent_abs_path in ignores_to_delete {
4100            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
4101            self.state
4102                .lock()
4103                .snapshot
4104                .ignores_by_parent_abs_path
4105                .remove(&parent_abs_path);
4106        }
4107
4108        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4109        ignores_to_update.sort_unstable();
4110        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
4111        while let Some(parent_abs_path) = ignores_to_update.next() {
4112            while ignores_to_update
4113                .peek()
4114                .map_or(false, |p| p.starts_with(&parent_abs_path))
4115            {
4116                ignores_to_update.next().unwrap();
4117            }
4118
4119            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
4120            smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
4121                abs_path: parent_abs_path,
4122                ignore_stack,
4123                ignore_queue: ignore_queue_tx.clone(),
4124                scan_queue: scan_job_tx.clone(),
4125            }))
4126            .unwrap();
4127        }
4128        drop(ignore_queue_tx);
4129
4130        self.executor
4131            .scoped(|scope| {
4132                for _ in 0..self.executor.num_cpus() {
4133                    scope.spawn(async {
4134                        loop {
4135                            select_biased! {
4136                                // Process any path refresh requests before moving on to process
4137                                // the queue of ignore statuses.
4138                                request = self.scan_requests_rx.recv().fuse() => {
4139                                    let Ok(request) = request else { break };
4140                                    if !self.process_scan_request(request, true).await {
4141                                        return;
4142                                    }
4143                                }
4144
4145                                // Recursively process directories whose ignores have changed.
4146                                job = ignore_queue_rx.recv().fuse() => {
4147                                    let Ok(job) = job else { break };
4148                                    self.update_ignore_status(job, &snapshot).await;
4149                                }
4150                            }
4151                        }
4152                    });
4153                }
4154            })
4155            .await;
4156    }
4157
4158    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4159        log::trace!("update ignore status {:?}", job.abs_path);
4160
4161        let mut ignore_stack = job.ignore_stack;
4162        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4163            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4164        }
4165
4166        let mut entries_by_id_edits = Vec::new();
4167        let mut entries_by_path_edits = Vec::new();
4168        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
4169        for mut entry in snapshot.child_entries(path).cloned() {
4170            let was_ignored = entry.is_ignored;
4171            let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4172            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4173            if entry.is_dir() {
4174                let child_ignore_stack = if entry.is_ignored {
4175                    IgnoreStack::all()
4176                } else {
4177                    ignore_stack.clone()
4178                };
4179
4180                // Scan any directories that were previously ignored and weren't previously scanned.
4181                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4182                    let state = self.state.lock();
4183                    if state.should_scan_directory(&entry) {
4184                        state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4185                    }
4186                }
4187
4188                job.ignore_queue
4189                    .send(UpdateIgnoreStatusJob {
4190                        abs_path: abs_path.clone(),
4191                        ignore_stack: child_ignore_stack,
4192                        ignore_queue: job.ignore_queue.clone(),
4193                        scan_queue: job.scan_queue.clone(),
4194                    })
4195                    .await
4196                    .unwrap();
4197            }
4198
4199            if entry.is_ignored != was_ignored {
4200                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
4201                path_entry.scan_id = snapshot.scan_id;
4202                path_entry.is_ignored = entry.is_ignored;
4203                entries_by_id_edits.push(Edit::Insert(path_entry));
4204                entries_by_path_edits.push(Edit::Insert(entry));
4205            }
4206        }
4207
4208        let state = &mut self.state.lock();
4209        for edit in &entries_by_path_edits {
4210            if let Edit::Insert(entry) = edit {
4211                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
4212                    state.changed_paths.insert(ix, entry.path.clone());
4213                }
4214            }
4215        }
4216
4217        state
4218            .snapshot
4219            .entries_by_path
4220            .edit(entries_by_path_edits, &());
4221        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4222    }
4223
4224    fn build_change_set(
4225        &self,
4226        old_snapshot: &Snapshot,
4227        new_snapshot: &Snapshot,
4228        event_paths: &[Arc<Path>],
4229    ) -> UpdatedEntriesSet {
4230        use BackgroundScannerPhase::*;
4231        use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4232
4233        // Identify which paths have changed. Use the known set of changed
4234        // parent paths to optimize the search.
4235        let mut changes = Vec::new();
4236        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
4237        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
4238        let mut last_newly_loaded_dir_path = None;
4239        old_paths.next(&());
4240        new_paths.next(&());
4241        for path in event_paths {
4242            let path = PathKey(path.clone());
4243            if old_paths.item().map_or(false, |e| e.path < path.0) {
4244                old_paths.seek_forward(&path, Bias::Left, &());
4245            }
4246            if new_paths.item().map_or(false, |e| e.path < path.0) {
4247                new_paths.seek_forward(&path, Bias::Left, &());
4248            }
4249            loop {
4250                match (old_paths.item(), new_paths.item()) {
4251                    (Some(old_entry), Some(new_entry)) => {
4252                        if old_entry.path > path.0
4253                            && new_entry.path > path.0
4254                            && !old_entry.path.starts_with(&path.0)
4255                            && !new_entry.path.starts_with(&path.0)
4256                        {
4257                            break;
4258                        }
4259
4260                        match Ord::cmp(&old_entry.path, &new_entry.path) {
4261                            Ordering::Less => {
4262                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
4263                                old_paths.next(&());
4264                            }
4265                            Ordering::Equal => {
4266                                if self.phase == EventsReceivedDuringInitialScan {
4267                                    if old_entry.id != new_entry.id {
4268                                        changes.push((
4269                                            old_entry.path.clone(),
4270                                            old_entry.id,
4271                                            Removed,
4272                                        ));
4273                                    }
4274                                    // If the worktree was not fully initialized when this event was generated,
4275                                    // we can't know whether this entry was added during the scan or whether
4276                                    // it was merely updated.
4277                                    changes.push((
4278                                        new_entry.path.clone(),
4279                                        new_entry.id,
4280                                        AddedOrUpdated,
4281                                    ));
4282                                } else if old_entry.id != new_entry.id {
4283                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
4284                                    changes.push((new_entry.path.clone(), new_entry.id, Added));
4285                                } else if old_entry != new_entry {
4286                                    if old_entry.kind.is_unloaded() {
4287                                        last_newly_loaded_dir_path = Some(&new_entry.path);
4288                                        changes.push((
4289                                            new_entry.path.clone(),
4290                                            new_entry.id,
4291                                            Loaded,
4292                                        ));
4293                                    } else {
4294                                        changes.push((
4295                                            new_entry.path.clone(),
4296                                            new_entry.id,
4297                                            Updated,
4298                                        ));
4299                                    }
4300                                }
4301                                old_paths.next(&());
4302                                new_paths.next(&());
4303                            }
4304                            Ordering::Greater => {
4305                                let is_newly_loaded = self.phase == InitialScan
4306                                    || last_newly_loaded_dir_path
4307                                        .as_ref()
4308                                        .map_or(false, |dir| new_entry.path.starts_with(&dir));
4309                                changes.push((
4310                                    new_entry.path.clone(),
4311                                    new_entry.id,
4312                                    if is_newly_loaded { Loaded } else { Added },
4313                                ));
4314                                new_paths.next(&());
4315                            }
4316                        }
4317                    }
4318                    (Some(old_entry), None) => {
4319                        changes.push((old_entry.path.clone(), old_entry.id, Removed));
4320                        old_paths.next(&());
4321                    }
4322                    (None, Some(new_entry)) => {
4323                        let is_newly_loaded = self.phase == InitialScan
4324                            || last_newly_loaded_dir_path
4325                                .as_ref()
4326                                .map_or(false, |dir| new_entry.path.starts_with(&dir));
4327                        changes.push((
4328                            new_entry.path.clone(),
4329                            new_entry.id,
4330                            if is_newly_loaded { Loaded } else { Added },
4331                        ));
4332                        new_paths.next(&());
4333                    }
4334                    (None, None) => break,
4335                }
4336            }
4337        }
4338
4339        changes.into()
4340    }
4341
4342    async fn progress_timer(&self, running: bool) {
4343        if !running {
4344            return futures::future::pending().await;
4345        }
4346
4347        #[cfg(any(test, feature = "test-support"))]
4348        if self.fs.is_fake() {
4349            return self.executor.simulate_random_delay().await;
4350        }
4351
4352        smol::Timer::after(FS_WATCH_LATENCY).await;
4353    }
4354}
4355
4356fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4357    let mut result = root_char_bag;
4358    result.extend(
4359        path.to_string_lossy()
4360            .chars()
4361            .map(|c| c.to_ascii_lowercase()),
4362    );
4363    result
4364}
4365
4366struct ScanJob {
4367    abs_path: Arc<Path>,
4368    path: Arc<Path>,
4369    ignore_stack: Arc<IgnoreStack>,
4370    scan_queue: Sender<ScanJob>,
4371    ancestor_inodes: TreeSet<u64>,
4372    is_external: bool,
4373    containing_repository: Option<(
4374        RepositoryWorkDirectory,
4375        Arc<Mutex<dyn GitRepository>>,
4376        TreeMap<RepoPath, GitFileStatus>,
4377    )>,
4378}
4379
4380struct UpdateIgnoreStatusJob {
4381    abs_path: Arc<Path>,
4382    ignore_stack: Arc<IgnoreStack>,
4383    ignore_queue: Sender<UpdateIgnoreStatusJob>,
4384    scan_queue: Sender<ScanJob>,
4385}
4386
4387pub trait WorktreeModelHandle {
4388    #[cfg(any(test, feature = "test-support"))]
4389    fn flush_fs_events<'a>(
4390        &self,
4391        cx: &'a mut gpui::TestAppContext,
4392    ) -> futures::future::LocalBoxFuture<'a, ()>;
4393}
4394
4395impl WorktreeModelHandle for Model<Worktree> {
4396    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4397    // occurred before the worktree was constructed. These events can cause the worktree to perform
4398    // extra directory scans, and emit extra scan-state notifications.
4399    //
4400    // This function mutates the worktree's directory and waits for those mutations to be picked up,
4401    // to ensure that all redundant FS events have already been processed.
4402    #[cfg(any(test, feature = "test-support"))]
4403    fn flush_fs_events<'a>(
4404        &self,
4405        cx: &'a mut gpui::TestAppContext,
4406    ) -> futures::future::LocalBoxFuture<'a, ()> {
4407        let file_name = "fs-event-sentinel";
4408
4409        let tree = self.clone();
4410        let (fs, root_path) = self.update(cx, |tree, _| {
4411            let tree = tree.as_local().unwrap();
4412            (tree.fs.clone(), tree.abs_path().clone())
4413        });
4414
4415        async move {
4416            fs.create_file(&root_path.join(file_name), Default::default())
4417                .await
4418                .unwrap();
4419
4420            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
4421                .await;
4422
4423            fs.remove_file(&root_path.join(file_name), Default::default())
4424                .await
4425                .unwrap();
4426            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
4427                .await;
4428
4429            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4430                .await;
4431        }
4432        .boxed_local()
4433    }
4434}
4435
4436#[derive(Clone, Debug)]
4437struct TraversalProgress<'a> {
4438    max_path: &'a Path,
4439    count: usize,
4440    non_ignored_count: usize,
4441    file_count: usize,
4442    non_ignored_file_count: usize,
4443}
4444
4445impl<'a> TraversalProgress<'a> {
4446    fn count(&self, include_dirs: bool, include_ignored: bool) -> usize {
4447        match (include_ignored, include_dirs) {
4448            (true, true) => self.count,
4449            (true, false) => self.file_count,
4450            (false, true) => self.non_ignored_count,
4451            (false, false) => self.non_ignored_file_count,
4452        }
4453    }
4454}
4455
4456impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
4457    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4458        self.max_path = summary.max_path.as_ref();
4459        self.count += summary.count;
4460        self.non_ignored_count += summary.non_ignored_count;
4461        self.file_count += summary.file_count;
4462        self.non_ignored_file_count += summary.non_ignored_file_count;
4463    }
4464}
4465
4466impl<'a> Default for TraversalProgress<'a> {
4467    fn default() -> Self {
4468        Self {
4469            max_path: Path::new(""),
4470            count: 0,
4471            non_ignored_count: 0,
4472            file_count: 0,
4473            non_ignored_file_count: 0,
4474        }
4475    }
4476}
4477
4478#[derive(Clone, Debug, Default, Copy)]
4479struct GitStatuses {
4480    added: usize,
4481    modified: usize,
4482    conflict: usize,
4483}
4484
4485impl AddAssign for GitStatuses {
4486    fn add_assign(&mut self, rhs: Self) {
4487        self.added += rhs.added;
4488        self.modified += rhs.modified;
4489        self.conflict += rhs.conflict;
4490    }
4491}
4492
4493impl Sub for GitStatuses {
4494    type Output = GitStatuses;
4495
4496    fn sub(self, rhs: Self) -> Self::Output {
4497        GitStatuses {
4498            added: self.added - rhs.added,
4499            modified: self.modified - rhs.modified,
4500            conflict: self.conflict - rhs.conflict,
4501        }
4502    }
4503}
4504
4505impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
4506    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4507        *self += summary.statuses
4508    }
4509}
4510
4511pub struct Traversal<'a> {
4512    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
4513    include_ignored: bool,
4514    include_dirs: bool,
4515}
4516
4517impl<'a> Traversal<'a> {
4518    pub fn advance(&mut self) -> bool {
4519        self.cursor.seek_forward(
4520            &TraversalTarget::Count {
4521                count: self.end_offset() + 1,
4522                include_dirs: self.include_dirs,
4523                include_ignored: self.include_ignored,
4524            },
4525            Bias::Left,
4526            &(),
4527        )
4528    }
4529
4530    pub fn advance_to_sibling(&mut self) -> bool {
4531        while let Some(entry) = self.cursor.item() {
4532            self.cursor.seek_forward(
4533                &TraversalTarget::PathSuccessor(&entry.path),
4534                Bias::Left,
4535                &(),
4536            );
4537            if let Some(entry) = self.cursor.item() {
4538                if (self.include_dirs || !entry.is_dir())
4539                    && (self.include_ignored || !entry.is_ignored)
4540                {
4541                    return true;
4542                }
4543            }
4544        }
4545        false
4546    }
4547
4548    pub fn entry(&self) -> Option<&'a Entry> {
4549        self.cursor.item()
4550    }
4551
4552    pub fn start_offset(&self) -> usize {
4553        self.cursor
4554            .start()
4555            .count(self.include_dirs, self.include_ignored)
4556    }
4557
4558    pub fn end_offset(&self) -> usize {
4559        self.cursor
4560            .end(&())
4561            .count(self.include_dirs, self.include_ignored)
4562    }
4563}
4564
4565impl<'a> Iterator for Traversal<'a> {
4566    type Item = &'a Entry;
4567
4568    fn next(&mut self) -> Option<Self::Item> {
4569        if let Some(item) = self.entry() {
4570            self.advance();
4571            Some(item)
4572        } else {
4573            None
4574        }
4575    }
4576}
4577
4578#[derive(Debug)]
4579enum TraversalTarget<'a> {
4580    Path(&'a Path),
4581    PathSuccessor(&'a Path),
4582    Count {
4583        count: usize,
4584        include_ignored: bool,
4585        include_dirs: bool,
4586    },
4587}
4588
4589impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
4590    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
4591        match self {
4592            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
4593            TraversalTarget::PathSuccessor(path) => {
4594                if !cursor_location.max_path.starts_with(path) {
4595                    Ordering::Equal
4596                } else {
4597                    Ordering::Greater
4598                }
4599            }
4600            TraversalTarget::Count {
4601                count,
4602                include_dirs,
4603                include_ignored,
4604            } => Ord::cmp(
4605                count,
4606                &cursor_location.count(*include_dirs, *include_ignored),
4607            ),
4608        }
4609    }
4610}
4611
4612impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
4613    for TraversalTarget<'b>
4614{
4615    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
4616        self.cmp(&cursor_location.0, &())
4617    }
4618}
4619
4620struct ChildEntriesIter<'a> {
4621    parent_path: &'a Path,
4622    traversal: Traversal<'a>,
4623}
4624
4625impl<'a> Iterator for ChildEntriesIter<'a> {
4626    type Item = &'a Entry;
4627
4628    fn next(&mut self) -> Option<Self::Item> {
4629        if let Some(item) = self.traversal.entry() {
4630            if item.path.starts_with(&self.parent_path) {
4631                self.traversal.advance_to_sibling();
4632                return Some(item);
4633            }
4634        }
4635        None
4636    }
4637}
4638
4639pub struct DescendentEntriesIter<'a> {
4640    parent_path: &'a Path,
4641    traversal: Traversal<'a>,
4642}
4643
4644impl<'a> Iterator for DescendentEntriesIter<'a> {
4645    type Item = &'a Entry;
4646
4647    fn next(&mut self) -> Option<Self::Item> {
4648        if let Some(item) = self.traversal.entry() {
4649            if item.path.starts_with(&self.parent_path) {
4650                self.traversal.advance();
4651                return Some(item);
4652            }
4653        }
4654        None
4655    }
4656}
4657
4658impl<'a> From<&'a Entry> for proto::Entry {
4659    fn from(entry: &'a Entry) -> Self {
4660        Self {
4661            id: entry.id.to_proto(),
4662            is_dir: entry.is_dir(),
4663            path: entry.path.to_string_lossy().into(),
4664            inode: entry.inode,
4665            mtime: Some(entry.mtime.into()),
4666            is_symlink: entry.is_symlink,
4667            is_ignored: entry.is_ignored,
4668            is_external: entry.is_external,
4669            git_status: entry.git_status.map(git_status_to_proto),
4670        }
4671    }
4672}
4673
4674impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
4675    type Error = anyhow::Error;
4676
4677    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
4678        if let Some(mtime) = entry.mtime {
4679            let kind = if entry.is_dir {
4680                EntryKind::Dir
4681            } else {
4682                let mut char_bag = *root_char_bag;
4683                char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
4684                EntryKind::File(char_bag)
4685            };
4686            let path: Arc<Path> = PathBuf::from(entry.path).into();
4687            Ok(Entry {
4688                id: ProjectEntryId::from_proto(entry.id),
4689                kind,
4690                path,
4691                inode: entry.inode,
4692                mtime: mtime.into(),
4693                is_symlink: entry.is_symlink,
4694                is_ignored: entry.is_ignored,
4695                is_external: entry.is_external,
4696                git_status: git_status_from_proto(entry.git_status),
4697                is_private: false,
4698            })
4699        } else {
4700            Err(anyhow!(
4701                "missing mtime in remote worktree entry {:?}",
4702                entry.path
4703            ))
4704        }
4705    }
4706}
4707
4708fn combine_git_statuses(
4709    staged: Option<GitFileStatus>,
4710    unstaged: Option<GitFileStatus>,
4711) -> Option<GitFileStatus> {
4712    if let Some(staged) = staged {
4713        if let Some(unstaged) = unstaged {
4714            if unstaged != staged {
4715                Some(GitFileStatus::Modified)
4716            } else {
4717                Some(staged)
4718            }
4719        } else {
4720            Some(staged)
4721        }
4722    } else {
4723        unstaged
4724    }
4725}
4726
4727fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
4728    git_status.and_then(|status| {
4729        proto::GitStatus::from_i32(status).map(|status| match status {
4730            proto::GitStatus::Added => GitFileStatus::Added,
4731            proto::GitStatus::Modified => GitFileStatus::Modified,
4732            proto::GitStatus::Conflict => GitFileStatus::Conflict,
4733        })
4734    })
4735}
4736
4737fn git_status_to_proto(status: GitFileStatus) -> i32 {
4738    match status {
4739        GitFileStatus::Added => proto::GitStatus::Added as i32,
4740        GitFileStatus::Modified => proto::GitStatus::Modified as i32,
4741        GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
4742    }
4743}