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