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