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