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