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