worktree.rs

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