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