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};
  29use gpui::{
  30    App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, Task,
  31};
  32use ignore::IgnoreStack;
  33use language::DiskState;
  34
  35use parking_lot::Mutex;
  36use paths::local_settings_folder_relative_path;
  37use postage::{
  38    barrier,
  39    prelude::{Sink as _, Stream as _},
  40    watch,
  41};
  42use rpc::{
  43    proto::{self, split_worktree_update, FromProto, ToProto},
  44    AnyProtoClient,
  45};
  46pub use settings::WorktreeId;
  47use settings::{Settings, SettingsLocation, SettingsStore};
  48use smallvec::{smallvec, SmallVec};
  49use smol::channel::{self, Sender};
  50use std::{
  51    any::Any,
  52    cmp::Ordering,
  53    collections::hash_map,
  54    convert::TryFrom,
  55    ffi::OsStr,
  56    fmt,
  57    future::Future,
  58    mem::{self},
  59    ops::{Deref, DerefMut},
  60    path::{Path, PathBuf},
  61    pin::Pin,
  62    sync::{
  63        atomic::{self, AtomicU32, AtomicUsize, Ordering::SeqCst},
  64        Arc,
  65    },
  66    time::{Duration, Instant},
  67};
  68use sum_tree::{
  69    Bias, Cursor, Edit, KeyedItem, SeekTarget, SumTree, Summary, TreeMap, TreeSet, Unit,
  70};
  71use text::{LineEnding, Rope};
  72use util::{
  73    paths::{home_dir, PathMatcher, SanitizedPath},
  74    ResultExt,
  75};
  76pub use worktree_settings::WorktreeSettings;
  77
  78#[cfg(feature = "test-support")]
  79pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  80#[cfg(not(feature = "test-support"))]
  81pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  82
  83/// A set of local or remote files that are being opened as part of a project.
  84/// Responsible for tracking related FS (for local)/collab (for remote) events and corresponding updates.
  85/// Stores git repositories data and the diagnostics for the file(s).
  86///
  87/// Has an absolute path, and may be set to be visible in Zed UI or not.
  88/// May correspond to a directory or a single file.
  89/// Possible examples:
  90/// * a drag and dropped file — may be added as an invisible, "ephemeral" entry to the current worktree
  91/// * a directory opened in Zed — may be added as a visible entry to the current worktree
  92///
  93/// Uses [`Entry`] to track the state of each file/directory, can look up absolute paths for entries.
  94pub enum Worktree {
  95    Local(LocalWorktree),
  96    Remote(RemoteWorktree),
  97}
  98
  99/// An entry, created in the worktree.
 100#[derive(Debug)]
 101pub enum CreatedEntry {
 102    /// Got created and indexed by the worktree, receiving a corresponding entry.
 103    Included(Entry),
 104    /// Got created, but not indexed due to falling under exclusion filters.
 105    Excluded { abs_path: PathBuf },
 106}
 107
 108pub struct LoadedFile {
 109    pub file: Arc<File>,
 110    pub text: String,
 111}
 112
 113pub struct LoadedBinaryFile {
 114    pub file: Arc<File>,
 115    pub content: Vec<u8>,
 116}
 117
 118pub struct LocalWorktree {
 119    snapshot: LocalSnapshot,
 120    scan_requests_tx: channel::Sender<ScanRequest>,
 121    path_prefixes_to_scan_tx: channel::Sender<PathPrefixScanRequest>,
 122    is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
 123    _background_scanner_tasks: Vec<Task<()>>,
 124    update_observer: Option<UpdateObservationState>,
 125    fs: Arc<dyn Fs>,
 126    fs_case_sensitive: bool,
 127    visible: bool,
 128    next_entry_id: Arc<AtomicUsize>,
 129    settings: WorktreeSettings,
 130    share_private_files: bool,
 131}
 132
 133pub struct PathPrefixScanRequest {
 134    path: Arc<Path>,
 135    done: SmallVec<[barrier::Sender; 1]>,
 136}
 137
 138struct ScanRequest {
 139    relative_paths: Vec<Arc<Path>>,
 140    done: SmallVec<[barrier::Sender; 1]>,
 141}
 142
 143pub struct RemoteWorktree {
 144    snapshot: Snapshot,
 145    background_snapshot: Arc<Mutex<(Snapshot, Vec<proto::UpdateWorktree>)>>,
 146    project_id: u64,
 147    client: AnyProtoClient,
 148    file_scan_inclusions: PathMatcher,
 149    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
 150    update_observer: Option<mpsc::UnboundedSender<proto::UpdateWorktree>>,
 151    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
 152    replica_id: ReplicaId,
 153    visible: bool,
 154    disconnected: bool,
 155}
 156
 157#[derive(Clone)]
 158pub struct Snapshot {
 159    id: WorktreeId,
 160    abs_path: SanitizedPath,
 161    root_name: String,
 162    root_char_bag: CharBag,
 163    entries_by_path: SumTree<Entry>,
 164    entries_by_id: SumTree<PathEntry>,
 165    always_included_entries: Vec<Arc<Path>>,
 166    repositories: SumTree<RepositoryEntry>,
 167
 168    /// A number that increases every time the worktree begins scanning
 169    /// a set of paths from the filesystem. This scanning could be caused
 170    /// by some operation performed on the worktree, such as reading or
 171    /// writing a file, or by an event reported by the filesystem.
 172    scan_id: usize,
 173
 174    /// The latest scan id that has completed, and whose preceding scans
 175    /// have all completed. The current `scan_id` could be more than one
 176    /// greater than the `completed_scan_id` if operations are performed
 177    /// on the worktree while it is processing a file-system event.
 178    completed_scan_id: usize,
 179}
 180
 181#[derive(Debug, Clone, PartialEq, Eq)]
 182pub struct RepositoryEntry {
 183    /// The git status entries for this repository.
 184    /// Note that the paths on this repository are relative to the git work directory.
 185    /// If the .git folder is external to Zed, these paths will be relative to that folder,
 186    /// and this data structure might reference files external to this worktree.
 187    ///
 188    /// For example:
 189    ///
 190    ///     my_root_folder/          <-- repository root
 191    ///       .git
 192    ///       my_sub_folder_1/
 193    ///         project_root/        <-- Project root, Zed opened here
 194    ///           changed_file_1     <-- File with changes, in worktree
 195    ///       my_sub_folder_2/
 196    ///         changed_file_2       <-- File with changes, out of worktree
 197    ///           ...
 198    ///
 199    /// With this setup, this field would contain 2 entries, like so:
 200    ///     - my_sub_folder_1/project_root/changed_file_1
 201    ///     - my_sub_folder_2/changed_file_2
 202    pub(crate) statuses_by_path: SumTree<StatusEntry>,
 203    work_directory_id: ProjectEntryId,
 204    pub work_directory: WorkDirectory,
 205    pub(crate) current_branch: Option<Branch>,
 206    pub current_merge_conflicts: TreeSet<RepoPath>,
 207}
 208
 209impl RepositoryEntry {
 210    pub fn relativize(&self, path: &Path) -> Result<RepoPath> {
 211        self.work_directory.relativize(path)
 212    }
 213
 214    pub fn unrelativize(&self, path: &RepoPath) -> Option<Arc<Path>> {
 215        self.work_directory.unrelativize(path)
 216    }
 217
 218    pub fn directory_contains(&self, path: impl AsRef<Path>) -> bool {
 219        self.work_directory.directory_contains(path)
 220    }
 221
 222    pub fn branch(&self) -> Option<&Branch> {
 223        self.current_branch.as_ref()
 224    }
 225
 226    pub fn work_directory_id(&self) -> ProjectEntryId {
 227        self.work_directory_id
 228    }
 229
 230    pub fn status(&self) -> impl Iterator<Item = StatusEntry> + '_ {
 231        self.statuses_by_path.iter().cloned()
 232    }
 233
 234    pub fn status_len(&self) -> usize {
 235        self.statuses_by_path.summary().item_summary.count
 236    }
 237
 238    pub fn status_summary(&self) -> GitSummary {
 239        self.statuses_by_path.summary().item_summary
 240    }
 241
 242    pub fn status_for_path(&self, path: &RepoPath) -> Option<StatusEntry> {
 243        self.statuses_by_path
 244            .get(&PathKey(path.0.clone()), &())
 245            .cloned()
 246    }
 247
 248    pub fn initial_update(&self) -> proto::RepositoryEntry {
 249        proto::RepositoryEntry {
 250            work_directory_id: self.work_directory_id.to_proto(),
 251            branch: self
 252                .current_branch
 253                .as_ref()
 254                .map(|branch| branch.name.to_string()),
 255            branch_summary: self.current_branch.as_ref().map(branch_to_proto),
 256            updated_statuses: self
 257                .statuses_by_path
 258                .iter()
 259                .map(|entry| entry.to_proto())
 260                .collect(),
 261            removed_statuses: Default::default(),
 262            current_merge_conflicts: self
 263                .current_merge_conflicts
 264                .iter()
 265                .map(|repo_path| repo_path.to_proto())
 266                .collect(),
 267        }
 268    }
 269
 270    pub fn build_update(&self, old: &Self) -> proto::RepositoryEntry {
 271        let mut updated_statuses: Vec<proto::StatusEntry> = Vec::new();
 272        let mut removed_statuses: Vec<String> = Vec::new();
 273
 274        let mut new_statuses = self.statuses_by_path.iter().peekable();
 275        let mut old_statuses = old.statuses_by_path.iter().peekable();
 276
 277        let mut current_new_entry = new_statuses.next();
 278        let mut current_old_entry = old_statuses.next();
 279        loop {
 280            match (current_new_entry, current_old_entry) {
 281                (Some(new_entry), Some(old_entry)) => {
 282                    match new_entry.repo_path.cmp(&old_entry.repo_path) {
 283                        Ordering::Less => {
 284                            updated_statuses.push(new_entry.to_proto());
 285                            current_new_entry = new_statuses.next();
 286                        }
 287                        Ordering::Equal => {
 288                            if new_entry.status != old_entry.status {
 289                                updated_statuses.push(new_entry.to_proto());
 290                            }
 291                            current_old_entry = old_statuses.next();
 292                            current_new_entry = new_statuses.next();
 293                        }
 294                        Ordering::Greater => {
 295                            removed_statuses.push(old_entry.repo_path.as_ref().to_proto());
 296                            current_old_entry = old_statuses.next();
 297                        }
 298                    }
 299                }
 300                (None, Some(old_entry)) => {
 301                    removed_statuses.push(old_entry.repo_path.as_ref().to_proto());
 302                    current_old_entry = old_statuses.next();
 303                }
 304                (Some(new_entry), None) => {
 305                    updated_statuses.push(new_entry.to_proto());
 306                    current_new_entry = new_statuses.next();
 307                }
 308                (None, None) => break,
 309            }
 310        }
 311
 312        proto::RepositoryEntry {
 313            work_directory_id: self.work_directory_id.to_proto(),
 314            branch: self
 315                .current_branch
 316                .as_ref()
 317                .map(|branch| branch.name.to_string()),
 318            branch_summary: self.current_branch.as_ref().map(branch_to_proto),
 319            updated_statuses,
 320            removed_statuses,
 321            current_merge_conflicts: self
 322                .current_merge_conflicts
 323                .iter()
 324                .map(|path| path.as_ref().to_proto())
 325                .collect(),
 326        }
 327    }
 328}
 329
 330pub fn branch_to_proto(branch: &git::repository::Branch) -> proto::Branch {
 331    proto::Branch {
 332        is_head: branch.is_head,
 333        name: branch.name.to_string(),
 334        unix_timestamp: branch
 335            .most_recent_commit
 336            .as_ref()
 337            .map(|commit| commit.commit_timestamp as u64),
 338        upstream: branch.upstream.as_ref().map(|upstream| proto::GitUpstream {
 339            ref_name: upstream.ref_name.to_string(),
 340            tracking: upstream
 341                .tracking
 342                .status()
 343                .map(|upstream| proto::UpstreamTracking {
 344                    ahead: upstream.ahead as u64,
 345                    behind: upstream.behind as u64,
 346                }),
 347        }),
 348        most_recent_commit: branch
 349            .most_recent_commit
 350            .as_ref()
 351            .map(|commit| proto::CommitSummary {
 352                sha: commit.sha.to_string(),
 353                subject: commit.subject.to_string(),
 354                commit_timestamp: commit.commit_timestamp,
 355            }),
 356    }
 357}
 358
 359pub fn proto_to_branch(proto: &proto::Branch) -> git::repository::Branch {
 360    git::repository::Branch {
 361        is_head: proto.is_head,
 362        name: proto.name.clone().into(),
 363        upstream: proto
 364            .upstream
 365            .as_ref()
 366            .map(|upstream| git::repository::Upstream {
 367                ref_name: upstream.ref_name.to_string().into(),
 368                tracking: upstream
 369                    .tracking
 370                    .as_ref()
 371                    .map(|tracking| {
 372                        git::repository::UpstreamTracking::Tracked(UpstreamTrackingStatus {
 373                            ahead: tracking.ahead as u32,
 374                            behind: tracking.behind as u32,
 375                        })
 376                    })
 377                    .unwrap_or(git::repository::UpstreamTracking::Gone),
 378            }),
 379        most_recent_commit: proto.most_recent_commit.as_ref().map(|commit| {
 380            git::repository::CommitSummary {
 381                sha: commit.sha.to_string().into(),
 382                subject: commit.subject.to_string().into(),
 383                commit_timestamp: commit.commit_timestamp,
 384            }
 385        }),
 386    }
 387}
 388
 389/// This path corresponds to the 'content path' of a repository in relation
 390/// to Zed's project root.
 391/// In the majority of the cases, this is the folder that contains the .git folder.
 392/// But if a sub-folder of a git repository is opened, this corresponds to the
 393/// project root and the .git folder is located in a parent directory.
 394#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
 395pub enum WorkDirectory {
 396    InProject {
 397        relative_path: Arc<Path>,
 398    },
 399    AboveProject {
 400        absolute_path: Arc<Path>,
 401        location_in_repo: Arc<Path>,
 402    },
 403}
 404
 405impl WorkDirectory {
 406    #[cfg(test)]
 407    fn in_project(path: &str) -> Self {
 408        let path = Path::new(path);
 409        Self::InProject {
 410            relative_path: path.into(),
 411        }
 412    }
 413
 414    #[cfg(test)]
 415    fn canonicalize(&self) -> Self {
 416        match self {
 417            WorkDirectory::InProject { relative_path } => WorkDirectory::InProject {
 418                relative_path: relative_path.clone(),
 419            },
 420            WorkDirectory::AboveProject {
 421                absolute_path,
 422                location_in_repo,
 423            } => WorkDirectory::AboveProject {
 424                absolute_path: absolute_path.canonicalize().unwrap().into(),
 425                location_in_repo: location_in_repo.clone(),
 426            },
 427        }
 428    }
 429
 430    pub fn is_above_project(&self) -> bool {
 431        match self {
 432            WorkDirectory::InProject { .. } => false,
 433            WorkDirectory::AboveProject { .. } => true,
 434        }
 435    }
 436
 437    fn path_key(&self) -> PathKey {
 438        match self {
 439            WorkDirectory::InProject { relative_path } => PathKey(relative_path.clone()),
 440            WorkDirectory::AboveProject { .. } => PathKey(Path::new("").into()),
 441        }
 442    }
 443
 444    /// Returns true if the given path is a child of the work directory.
 445    ///
 446    /// Note that the path may not be a member of this repository, if there
 447    /// is a repository in a directory between these two paths
 448    /// external .git folder in a parent folder of the project root.
 449    #[track_caller]
 450    pub fn directory_contains(&self, path: impl AsRef<Path>) -> bool {
 451        let path = path.as_ref();
 452        debug_assert!(path.is_relative());
 453        match self {
 454            WorkDirectory::InProject { relative_path } => path.starts_with(relative_path),
 455            WorkDirectory::AboveProject { .. } => true,
 456        }
 457    }
 458
 459    /// relativize returns the given project path relative to the root folder of the
 460    /// repository.
 461    /// If the root of the repository (and its .git folder) are located in a parent folder
 462    /// of the project root folder, then the returned RepoPath is relative to the root
 463    /// of the repository and not a valid path inside the project.
 464    pub fn relativize(&self, path: &Path) -> Result<RepoPath> {
 465        // path is assumed to be relative to worktree root.
 466        debug_assert!(path.is_relative());
 467        match self {
 468            WorkDirectory::InProject { relative_path } => Ok(path
 469                .strip_prefix(relative_path)
 470                .map_err(|_| {
 471                    anyhow!(
 472                        "could not relativize {:?} against {:?}",
 473                        path,
 474                        relative_path
 475                    )
 476                })?
 477                .into()),
 478            WorkDirectory::AboveProject {
 479                location_in_repo, ..
 480            } => {
 481                // Avoid joining a `/` to location_in_repo in the case of a single-file worktree.
 482                if path == Path::new("") {
 483                    Ok(RepoPath(location_in_repo.clone()))
 484                } else {
 485                    Ok(location_in_repo.join(path).into())
 486                }
 487            }
 488        }
 489    }
 490
 491    /// This is the opposite operation to `relativize` above
 492    pub fn unrelativize(&self, path: &RepoPath) -> Option<Arc<Path>> {
 493        match self {
 494            WorkDirectory::InProject { relative_path } => Some(relative_path.join(path).into()),
 495            WorkDirectory::AboveProject {
 496                location_in_repo, ..
 497            } => {
 498                // If we fail to strip the prefix, that means this status entry is
 499                // external to this worktree, and we definitely won't have an entry_id
 500                path.strip_prefix(location_in_repo).ok().map(Into::into)
 501            }
 502        }
 503    }
 504
 505    pub fn display_name(&self) -> String {
 506        match self {
 507            WorkDirectory::InProject { relative_path } => relative_path.display().to_string(),
 508            WorkDirectory::AboveProject {
 509                absolute_path,
 510                location_in_repo,
 511            } => {
 512                let num_of_dots = location_in_repo.components().count();
 513
 514                "../".repeat(num_of_dots)
 515                    + &absolute_path
 516                        .file_name()
 517                        .map(|s| s.to_string_lossy())
 518                        .unwrap_or_default()
 519                    + "/"
 520            }
 521        }
 522    }
 523}
 524
 525impl Default for WorkDirectory {
 526    fn default() -> Self {
 527        Self::InProject {
 528            relative_path: Arc::from(Path::new("")),
 529        }
 530    }
 531}
 532
 533#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
 534pub struct WorkDirectoryEntry(ProjectEntryId);
 535
 536impl Deref for WorkDirectoryEntry {
 537    type Target = ProjectEntryId;
 538
 539    fn deref(&self) -> &Self::Target {
 540        &self.0
 541    }
 542}
 543
 544impl From<ProjectEntryId> for WorkDirectoryEntry {
 545    fn from(value: ProjectEntryId) -> Self {
 546        WorkDirectoryEntry(value)
 547    }
 548}
 549
 550#[derive(Debug, Clone)]
 551pub struct LocalSnapshot {
 552    snapshot: Snapshot,
 553    /// All of the gitignore files in the worktree, indexed by their relative path.
 554    /// The boolean indicates whether the gitignore needs to be updated.
 555    ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
 556    /// All of the git repositories in the worktree, indexed by the project entry
 557    /// id of their parent directory.
 558    git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
 559    /// The file handle of the root dir
 560    /// (so we can find it after it's been moved)
 561    root_file_handle: Option<Arc<dyn fs::FileHandle>>,
 562}
 563
 564struct BackgroundScannerState {
 565    snapshot: LocalSnapshot,
 566    scanned_dirs: HashSet<ProjectEntryId>,
 567    path_prefixes_to_scan: HashSet<Arc<Path>>,
 568    paths_to_scan: HashSet<Arc<Path>>,
 569    /// The ids of all of the entries that were removed from the snapshot
 570    /// as part of the current update. These entry ids may be re-used
 571    /// if the same inode is discovered at a new path, or if the given
 572    /// path is re-created after being deleted.
 573    removed_entries: HashMap<u64, Entry>,
 574    changed_paths: Vec<Arc<Path>>,
 575    prev_snapshot: Snapshot,
 576    git_hosting_provider_registry: Option<Arc<GitHostingProviderRegistry>>,
 577    repository_scans: HashMap<PathKey, Task<()>>,
 578}
 579
 580#[derive(Debug, Clone)]
 581pub struct LocalRepositoryEntry {
 582    pub(crate) work_directory_id: ProjectEntryId,
 583    pub(crate) work_directory: WorkDirectory,
 584    pub(crate) git_dir_scan_id: usize,
 585    pub(crate) status_scan_id: usize,
 586    pub(crate) repo_ptr: Arc<dyn GitRepository>,
 587    /// Absolute path to the actual .git folder.
 588    /// Note: if .git is a file, this points to the folder indicated by the .git file
 589    pub(crate) dot_git_dir_abs_path: Arc<Path>,
 590    /// Absolute path to the .git file, if we're in a git worktree.
 591    pub(crate) dot_git_worktree_abs_path: Option<Arc<Path>>,
 592    pub current_merge_head_shas: Vec<String>,
 593    pub merge_message: Option<String>,
 594}
 595
 596impl sum_tree::Item for LocalRepositoryEntry {
 597    type Summary = PathSummary<Unit>;
 598
 599    fn summary(&self, _: &<Self::Summary as Summary>::Context) -> Self::Summary {
 600        PathSummary {
 601            max_path: self.work_directory.path_key().0,
 602            item_summary: Unit,
 603        }
 604    }
 605}
 606
 607impl KeyedItem for LocalRepositoryEntry {
 608    type Key = PathKey;
 609
 610    fn key(&self) -> Self::Key {
 611        self.work_directory.path_key()
 612    }
 613}
 614
 615impl LocalRepositoryEntry {
 616    pub fn repo(&self) -> &Arc<dyn GitRepository> {
 617        &self.repo_ptr
 618    }
 619}
 620
 621impl Deref for LocalRepositoryEntry {
 622    type Target = WorkDirectory;
 623
 624    fn deref(&self) -> &Self::Target {
 625        &self.work_directory
 626    }
 627}
 628
 629impl Deref for LocalSnapshot {
 630    type Target = Snapshot;
 631
 632    fn deref(&self) -> &Self::Target {
 633        &self.snapshot
 634    }
 635}
 636
 637impl DerefMut for LocalSnapshot {
 638    fn deref_mut(&mut self) -> &mut Self::Target {
 639        &mut self.snapshot
 640    }
 641}
 642
 643#[derive(Debug)]
 644enum ScanState {
 645    Started,
 646    Updated {
 647        snapshot: LocalSnapshot,
 648        changes: UpdatedEntriesSet,
 649        barrier: SmallVec<[barrier::Sender; 1]>,
 650        scanning: bool,
 651    },
 652    RootUpdated {
 653        new_path: Option<SanitizedPath>,
 654    },
 655}
 656
 657struct UpdateObservationState {
 658    snapshots_tx:
 659        mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>,
 660    resume_updates: watch::Sender<()>,
 661    _maintain_remote_snapshot: Task<Option<()>>,
 662}
 663
 664#[derive(Clone)]
 665pub enum Event {
 666    UpdatedEntries(UpdatedEntriesSet),
 667    UpdatedGitRepositories(UpdatedGitRepositoriesSet),
 668    DeletedEntry(ProjectEntryId),
 669}
 670
 671const EMPTY_PATH: &str = "";
 672
 673impl EventEmitter<Event> for Worktree {}
 674
 675impl Worktree {
 676    pub async fn local(
 677        path: impl Into<Arc<Path>>,
 678        visible: bool,
 679        fs: Arc<dyn Fs>,
 680        next_entry_id: Arc<AtomicUsize>,
 681        cx: &mut AsyncApp,
 682    ) -> Result<Entity<Self>> {
 683        let abs_path = path.into();
 684        let metadata = fs
 685            .metadata(&abs_path)
 686            .await
 687            .context("failed to stat worktree path")?;
 688
 689        let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
 690            log::error!(
 691                "Failed to determine whether filesystem is case sensitive (falling back to true) due to error: {e:#}"
 692            );
 693            true
 694        });
 695
 696        let root_file_handle = fs.open_handle(&abs_path).await.log_err();
 697
 698        cx.new(move |cx: &mut Context<Worktree>| {
 699            let mut snapshot = LocalSnapshot {
 700                ignores_by_parent_abs_path: Default::default(),
 701                git_repositories: Default::default(),
 702                snapshot: Snapshot::new(
 703                    cx.entity_id().as_u64(),
 704                    abs_path
 705                        .file_name()
 706                        .map_or(String::new(), |f| f.to_string_lossy().to_string()),
 707                    abs_path.clone(),
 708                ),
 709                root_file_handle,
 710            };
 711
 712            let worktree_id = snapshot.id();
 713            let settings_location = Some(SettingsLocation {
 714                worktree_id,
 715                path: Path::new(EMPTY_PATH),
 716            });
 717
 718            let settings = WorktreeSettings::get(settings_location, cx).clone();
 719            cx.observe_global::<SettingsStore>(move |this, cx| {
 720                if let Self::Local(this) = this {
 721                    let settings = WorktreeSettings::get(settings_location, cx).clone();
 722                    if this.settings != settings {
 723                        this.settings = settings;
 724                        this.restart_background_scanners(cx);
 725                    }
 726                }
 727            })
 728            .detach();
 729
 730            let share_private_files = false;
 731            if let Some(metadata) = metadata {
 732                let mut entry = Entry::new(
 733                    Arc::from(Path::new("")),
 734                    &metadata,
 735                    &next_entry_id,
 736                    snapshot.root_char_bag,
 737                    None,
 738                );
 739                if !metadata.is_dir {
 740                    entry.is_private = !share_private_files
 741                        && settings.is_path_private(abs_path.file_name().unwrap().as_ref());
 742                }
 743                snapshot.insert_entry(entry, fs.as_ref());
 744            }
 745
 746            let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
 747            let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
 748            let mut worktree = LocalWorktree {
 749                share_private_files,
 750                next_entry_id,
 751                snapshot,
 752                is_scanning: watch::channel_with(true),
 753                update_observer: None,
 754                scan_requests_tx,
 755                path_prefixes_to_scan_tx,
 756                _background_scanner_tasks: Vec::new(),
 757                fs,
 758                fs_case_sensitive,
 759                visible,
 760                settings,
 761            };
 762            worktree.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
 763            Worktree::Local(worktree)
 764        })
 765    }
 766
 767    pub fn remote(
 768        project_id: u64,
 769        replica_id: ReplicaId,
 770        worktree: proto::WorktreeMetadata,
 771        client: AnyProtoClient,
 772        cx: &mut App,
 773    ) -> Entity<Self> {
 774        cx.new(|cx: &mut Context<Self>| {
 775            let snapshot = Snapshot::new(
 776                worktree.id,
 777                worktree.root_name,
 778                Arc::<Path>::from_proto(worktree.abs_path),
 779            );
 780
 781            let background_snapshot = Arc::new(Mutex::new((snapshot.clone(), Vec::new())));
 782            let (background_updates_tx, mut background_updates_rx) = mpsc::unbounded();
 783            let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 784
 785            let worktree_id = snapshot.id();
 786            let settings_location = Some(SettingsLocation {
 787                worktree_id,
 788                path: Path::new(EMPTY_PATH),
 789            });
 790
 791            let settings = WorktreeSettings::get(settings_location, cx).clone();
 792            let worktree = RemoteWorktree {
 793                client,
 794                project_id,
 795                replica_id,
 796                snapshot,
 797                file_scan_inclusions: settings.file_scan_inclusions.clone(),
 798                background_snapshot: background_snapshot.clone(),
 799                updates_tx: Some(background_updates_tx),
 800                update_observer: None,
 801                snapshot_subscriptions: Default::default(),
 802                visible: worktree.visible,
 803                disconnected: false,
 804            };
 805
 806            // Apply updates to a separate snapshot in a background task, then
 807            // send them to a foreground task which updates the model.
 808            cx.background_spawn(async move {
 809                while let Some(update) = background_updates_rx.next().await {
 810                    {
 811                        let mut lock = background_snapshot.lock();
 812                        if let Err(error) = lock
 813                            .0
 814                            .apply_remote_update(update.clone(), &settings.file_scan_inclusions)
 815                        {
 816                            log::error!("error applying worktree update: {}", error);
 817                        }
 818                        lock.1.push(update);
 819                    }
 820                    snapshot_updated_tx.send(()).await.ok();
 821                }
 822            })
 823            .detach();
 824
 825            // On the foreground task, update to the latest snapshot and notify
 826            // any update observer of all updates that led to that snapshot.
 827            cx.spawn(|this, mut cx| async move {
 828                while (snapshot_updated_rx.recv().await).is_some() {
 829                    this.update(&mut cx, |this, cx| {
 830                        let mut git_repos_changed = false;
 831                        let mut entries_changed = false;
 832                        let this = this.as_remote_mut().unwrap();
 833                        {
 834                            let mut lock = this.background_snapshot.lock();
 835                            this.snapshot = lock.0.clone();
 836                            for update in lock.1.drain(..) {
 837                                if !update.updated_entries.is_empty()
 838                                    || !update.removed_entries.is_empty()
 839                                {
 840                                    entries_changed = true;
 841                                }
 842                                if !update.updated_repositories.is_empty()
 843                                    || !update.removed_repositories.is_empty()
 844                                {
 845                                    git_repos_changed = true;
 846                                }
 847                                if let Some(tx) = &this.update_observer {
 848                                    tx.unbounded_send(update).ok();
 849                                }
 850                            }
 851                        };
 852
 853                        if entries_changed {
 854                            cx.emit(Event::UpdatedEntries(Arc::default()));
 855                        }
 856                        if git_repos_changed {
 857                            cx.emit(Event::UpdatedGitRepositories(Arc::default()));
 858                        }
 859                        cx.notify();
 860                        while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 861                            if this.observed_snapshot(*scan_id) {
 862                                let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 863                                let _ = tx.send(());
 864                            } else {
 865                                break;
 866                            }
 867                        }
 868                    })?;
 869                }
 870                anyhow::Ok(())
 871            })
 872            .detach();
 873
 874            Worktree::Remote(worktree)
 875        })
 876    }
 877
 878    pub fn as_local(&self) -> Option<&LocalWorktree> {
 879        if let Worktree::Local(worktree) = self {
 880            Some(worktree)
 881        } else {
 882            None
 883        }
 884    }
 885
 886    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 887        if let Worktree::Remote(worktree) = self {
 888            Some(worktree)
 889        } else {
 890            None
 891        }
 892    }
 893
 894    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 895        if let Worktree::Local(worktree) = self {
 896            Some(worktree)
 897        } else {
 898            None
 899        }
 900    }
 901
 902    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 903        if let Worktree::Remote(worktree) = self {
 904            Some(worktree)
 905        } else {
 906            None
 907        }
 908    }
 909
 910    pub fn is_local(&self) -> bool {
 911        matches!(self, Worktree::Local(_))
 912    }
 913
 914    pub fn is_remote(&self) -> bool {
 915        !self.is_local()
 916    }
 917
 918    pub fn settings_location(&self, _: &Context<Self>) -> SettingsLocation<'static> {
 919        SettingsLocation {
 920            worktree_id: self.id(),
 921            path: Path::new(EMPTY_PATH),
 922        }
 923    }
 924
 925    pub fn snapshot(&self) -> Snapshot {
 926        match self {
 927            Worktree::Local(worktree) => worktree.snapshot.snapshot.clone(),
 928            Worktree::Remote(worktree) => worktree.snapshot.clone(),
 929        }
 930    }
 931
 932    pub fn scan_id(&self) -> usize {
 933        match self {
 934            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 935            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 936        }
 937    }
 938
 939    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
 940        proto::WorktreeMetadata {
 941            id: self.id().to_proto(),
 942            root_name: self.root_name().to_string(),
 943            visible: self.is_visible(),
 944            abs_path: self.abs_path().to_proto(),
 945        }
 946    }
 947
 948    pub fn completed_scan_id(&self) -> usize {
 949        match self {
 950            Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
 951            Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
 952        }
 953    }
 954
 955    pub fn is_visible(&self) -> bool {
 956        match self {
 957            Worktree::Local(worktree) => worktree.visible,
 958            Worktree::Remote(worktree) => worktree.visible,
 959        }
 960    }
 961
 962    pub fn replica_id(&self) -> ReplicaId {
 963        match self {
 964            Worktree::Local(_) => 0,
 965            Worktree::Remote(worktree) => worktree.replica_id,
 966        }
 967    }
 968
 969    pub fn abs_path(&self) -> Arc<Path> {
 970        match self {
 971            Worktree::Local(worktree) => worktree.abs_path.clone().into(),
 972            Worktree::Remote(worktree) => worktree.abs_path.clone().into(),
 973        }
 974    }
 975
 976    pub fn root_file(&self, cx: &Context<Self>) -> Option<Arc<File>> {
 977        let entry = self.root_entry()?;
 978        Some(File::for_entry(entry.clone(), cx.entity()))
 979    }
 980
 981    pub fn observe_updates<F, Fut>(&mut self, project_id: u64, cx: &Context<Worktree>, callback: F)
 982    where
 983        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
 984        Fut: 'static + Send + Future<Output = bool>,
 985    {
 986        match self {
 987            Worktree::Local(this) => this.observe_updates(project_id, cx, callback),
 988            Worktree::Remote(this) => this.observe_updates(project_id, cx, callback),
 989        }
 990    }
 991
 992    pub fn stop_observing_updates(&mut self) {
 993        match self {
 994            Worktree::Local(this) => {
 995                this.update_observer.take();
 996            }
 997            Worktree::Remote(this) => {
 998                this.update_observer.take();
 999            }
1000        }
1001    }
1002
1003    #[cfg(any(test, feature = "test-support"))]
1004    pub fn has_update_observer(&self) -> bool {
1005        match self {
1006            Worktree::Local(this) => this.update_observer.is_some(),
1007            Worktree::Remote(this) => this.update_observer.is_some(),
1008        }
1009    }
1010
1011    pub fn load_file(&self, path: &Path, cx: &Context<Worktree>) -> Task<Result<LoadedFile>> {
1012        match self {
1013            Worktree::Local(this) => this.load_file(path, cx),
1014            Worktree::Remote(_) => {
1015                Task::ready(Err(anyhow!("remote worktrees can't yet load files")))
1016            }
1017        }
1018    }
1019
1020    pub fn load_staged_file(&self, path: &Path, cx: &App) -> Task<Result<Option<String>>> {
1021        match self {
1022            Worktree::Local(this) => {
1023                let path = Arc::from(path);
1024                let snapshot = this.snapshot();
1025                cx.background_spawn(async move {
1026                    if let Some(repo) = snapshot.repository_for_path(&path) {
1027                        if let Some(repo_path) = repo.relativize(&path).log_err() {
1028                            if let Some(git_repo) =
1029                                snapshot.git_repositories.get(&repo.work_directory_id)
1030                            {
1031                                return Ok(git_repo.repo_ptr.load_index_text(&repo_path));
1032                            }
1033                        }
1034                    }
1035                    Err(anyhow!("No repository found for {path:?}"))
1036                })
1037            }
1038            Worktree::Remote(_) => {
1039                Task::ready(Err(anyhow!("remote worktrees can't yet load staged files")))
1040            }
1041        }
1042    }
1043
1044    pub fn load_committed_file(&self, path: &Path, cx: &App) -> Task<Result<Option<String>>> {
1045        match self {
1046            Worktree::Local(this) => {
1047                let path = Arc::from(path);
1048                let snapshot = this.snapshot();
1049                cx.background_spawn(async move {
1050                    if let Some(repo) = snapshot.repository_for_path(&path) {
1051                        if let Some(repo_path) = repo.relativize(&path).log_err() {
1052                            if let Some(git_repo) =
1053                                snapshot.git_repositories.get(&repo.work_directory_id)
1054                            {
1055                                return Ok(git_repo.repo_ptr.load_committed_text(&repo_path));
1056                            }
1057                        }
1058                    }
1059                    Err(anyhow!("No repository found for {path:?}"))
1060                })
1061            }
1062            Worktree::Remote(_) => Task::ready(Err(anyhow!(
1063                "remote worktrees can't yet load committed files"
1064            ))),
1065        }
1066    }
1067
1068    pub fn load_binary_file(
1069        &self,
1070        path: &Path,
1071        cx: &Context<Worktree>,
1072    ) -> Task<Result<LoadedBinaryFile>> {
1073        match self {
1074            Worktree::Local(this) => this.load_binary_file(path, cx),
1075            Worktree::Remote(_) => {
1076                Task::ready(Err(anyhow!("remote worktrees can't yet load binary files")))
1077            }
1078        }
1079    }
1080
1081    pub fn write_file(
1082        &self,
1083        path: &Path,
1084        text: Rope,
1085        line_ending: LineEnding,
1086        cx: &Context<Worktree>,
1087    ) -> Task<Result<Arc<File>>> {
1088        match self {
1089            Worktree::Local(this) => this.write_file(path, text, line_ending, cx),
1090            Worktree::Remote(_) => {
1091                Task::ready(Err(anyhow!("remote worktree can't yet write files")))
1092            }
1093        }
1094    }
1095
1096    pub fn create_entry(
1097        &mut self,
1098        path: impl Into<Arc<Path>>,
1099        is_directory: bool,
1100        cx: &Context<Worktree>,
1101    ) -> Task<Result<CreatedEntry>> {
1102        let path: Arc<Path> = path.into();
1103        let worktree_id = self.id();
1104        match self {
1105            Worktree::Local(this) => this.create_entry(path, is_directory, cx),
1106            Worktree::Remote(this) => {
1107                let project_id = this.project_id;
1108                let request = this.client.request(proto::CreateProjectEntry {
1109                    worktree_id: worktree_id.to_proto(),
1110                    project_id,
1111                    path: path.as_ref().to_proto(),
1112                    is_directory,
1113                });
1114                cx.spawn(move |this, mut cx| async move {
1115                    let response = request.await?;
1116                    match response.entry {
1117                        Some(entry) => this
1118                            .update(&mut cx, |worktree, cx| {
1119                                worktree.as_remote_mut().unwrap().insert_entry(
1120                                    entry,
1121                                    response.worktree_scan_id as usize,
1122                                    cx,
1123                                )
1124                            })?
1125                            .await
1126                            .map(CreatedEntry::Included),
1127                        None => {
1128                            let abs_path = this.update(&mut cx, |worktree, _| {
1129                                worktree
1130                                    .absolutize(&path)
1131                                    .with_context(|| format!("absolutizing {path:?}"))
1132                            })??;
1133                            Ok(CreatedEntry::Excluded { abs_path })
1134                        }
1135                    }
1136                })
1137            }
1138        }
1139    }
1140
1141    pub fn delete_entry(
1142        &mut self,
1143        entry_id: ProjectEntryId,
1144        trash: bool,
1145        cx: &mut Context<Worktree>,
1146    ) -> Option<Task<Result<()>>> {
1147        let task = match self {
1148            Worktree::Local(this) => this.delete_entry(entry_id, trash, cx),
1149            Worktree::Remote(this) => this.delete_entry(entry_id, trash, cx),
1150        }?;
1151
1152        let entry = match self {
1153            Worktree::Local(ref this) => this.entry_for_id(entry_id),
1154            Worktree::Remote(ref this) => this.entry_for_id(entry_id),
1155        }?;
1156
1157        let mut ids = vec![entry_id];
1158        let path = &*entry.path;
1159
1160        self.get_children_ids_recursive(path, &mut ids);
1161
1162        for id in ids {
1163            cx.emit(Event::DeletedEntry(id));
1164        }
1165        Some(task)
1166    }
1167
1168    fn get_children_ids_recursive(&self, path: &Path, ids: &mut Vec<ProjectEntryId>) {
1169        let children_iter = self.child_entries(path);
1170        for child in children_iter {
1171            ids.push(child.id);
1172            self.get_children_ids_recursive(&child.path, ids);
1173        }
1174    }
1175
1176    pub fn rename_entry(
1177        &mut self,
1178        entry_id: ProjectEntryId,
1179        new_path: impl Into<Arc<Path>>,
1180        cx: &Context<Self>,
1181    ) -> Task<Result<CreatedEntry>> {
1182        let new_path = new_path.into();
1183        match self {
1184            Worktree::Local(this) => this.rename_entry(entry_id, new_path, cx),
1185            Worktree::Remote(this) => this.rename_entry(entry_id, new_path, cx),
1186        }
1187    }
1188
1189    pub fn copy_entry(
1190        &mut self,
1191        entry_id: ProjectEntryId,
1192        relative_worktree_source_path: Option<PathBuf>,
1193        new_path: impl Into<Arc<Path>>,
1194        cx: &Context<Self>,
1195    ) -> Task<Result<Option<Entry>>> {
1196        let new_path: Arc<Path> = new_path.into();
1197        match self {
1198            Worktree::Local(this) => {
1199                this.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1200            }
1201            Worktree::Remote(this) => {
1202                let relative_worktree_source_path = relative_worktree_source_path
1203                    .map(|relative_worktree_source_path| relative_worktree_source_path.to_proto());
1204                let response = this.client.request(proto::CopyProjectEntry {
1205                    project_id: this.project_id,
1206                    entry_id: entry_id.to_proto(),
1207                    relative_worktree_source_path,
1208                    new_path: new_path.to_proto(),
1209                });
1210                cx.spawn(move |this, mut cx| async move {
1211                    let response = response.await?;
1212                    match response.entry {
1213                        Some(entry) => this
1214                            .update(&mut cx, |worktree, cx| {
1215                                worktree.as_remote_mut().unwrap().insert_entry(
1216                                    entry,
1217                                    response.worktree_scan_id as usize,
1218                                    cx,
1219                                )
1220                            })?
1221                            .await
1222                            .map(Some),
1223                        None => Ok(None),
1224                    }
1225                })
1226            }
1227        }
1228    }
1229
1230    pub fn copy_external_entries(
1231        &mut self,
1232        target_directory: PathBuf,
1233        paths: Vec<Arc<Path>>,
1234        overwrite_existing_files: bool,
1235        cx: &Context<Worktree>,
1236    ) -> Task<Result<Vec<ProjectEntryId>>> {
1237        match self {
1238            Worktree::Local(this) => {
1239                this.copy_external_entries(target_directory, paths, overwrite_existing_files, cx)
1240            }
1241            _ => Task::ready(Err(anyhow!(
1242                "Copying external entries is not supported for remote worktrees"
1243            ))),
1244        }
1245    }
1246
1247    pub fn expand_entry(
1248        &mut self,
1249        entry_id: ProjectEntryId,
1250        cx: &Context<Worktree>,
1251    ) -> Option<Task<Result<()>>> {
1252        match self {
1253            Worktree::Local(this) => this.expand_entry(entry_id, cx),
1254            Worktree::Remote(this) => {
1255                let response = this.client.request(proto::ExpandProjectEntry {
1256                    project_id: this.project_id,
1257                    entry_id: entry_id.to_proto(),
1258                });
1259                Some(cx.spawn(move |this, mut cx| async move {
1260                    let response = response.await?;
1261                    this.update(&mut cx, |this, _| {
1262                        this.as_remote_mut()
1263                            .unwrap()
1264                            .wait_for_snapshot(response.worktree_scan_id as usize)
1265                    })?
1266                    .await?;
1267                    Ok(())
1268                }))
1269            }
1270        }
1271    }
1272
1273    pub fn expand_all_for_entry(
1274        &mut self,
1275        entry_id: ProjectEntryId,
1276        cx: &Context<Worktree>,
1277    ) -> Option<Task<Result<()>>> {
1278        match self {
1279            Worktree::Local(this) => this.expand_all_for_entry(entry_id, cx),
1280            Worktree::Remote(this) => {
1281                let response = this.client.request(proto::ExpandAllForProjectEntry {
1282                    project_id: this.project_id,
1283                    entry_id: entry_id.to_proto(),
1284                });
1285                Some(cx.spawn(move |this, mut cx| async move {
1286                    let response = response.await?;
1287                    this.update(&mut cx, |this, _| {
1288                        this.as_remote_mut()
1289                            .unwrap()
1290                            .wait_for_snapshot(response.worktree_scan_id as usize)
1291                    })?
1292                    .await?;
1293                    Ok(())
1294                }))
1295            }
1296        }
1297    }
1298
1299    pub async fn handle_create_entry(
1300        this: Entity<Self>,
1301        request: proto::CreateProjectEntry,
1302        mut cx: AsyncApp,
1303    ) -> Result<proto::ProjectEntryResponse> {
1304        let (scan_id, entry) = this.update(&mut cx, |this, cx| {
1305            (
1306                this.scan_id(),
1307                this.create_entry(
1308                    Arc::<Path>::from_proto(request.path),
1309                    request.is_directory,
1310                    cx,
1311                ),
1312            )
1313        })?;
1314        Ok(proto::ProjectEntryResponse {
1315            entry: match &entry.await? {
1316                CreatedEntry::Included(entry) => Some(entry.into()),
1317                CreatedEntry::Excluded { .. } => None,
1318            },
1319            worktree_scan_id: scan_id as u64,
1320        })
1321    }
1322
1323    pub async fn handle_delete_entry(
1324        this: Entity<Self>,
1325        request: proto::DeleteProjectEntry,
1326        mut cx: AsyncApp,
1327    ) -> Result<proto::ProjectEntryResponse> {
1328        let (scan_id, task) = this.update(&mut cx, |this, cx| {
1329            (
1330                this.scan_id(),
1331                this.delete_entry(
1332                    ProjectEntryId::from_proto(request.entry_id),
1333                    request.use_trash,
1334                    cx,
1335                ),
1336            )
1337        })?;
1338        task.ok_or_else(|| anyhow!("invalid entry"))?.await?;
1339        Ok(proto::ProjectEntryResponse {
1340            entry: None,
1341            worktree_scan_id: scan_id as u64,
1342        })
1343    }
1344
1345    pub async fn handle_expand_entry(
1346        this: Entity<Self>,
1347        request: proto::ExpandProjectEntry,
1348        mut cx: AsyncApp,
1349    ) -> Result<proto::ExpandProjectEntryResponse> {
1350        let task = this.update(&mut cx, |this, cx| {
1351            this.expand_entry(ProjectEntryId::from_proto(request.entry_id), cx)
1352        })?;
1353        task.ok_or_else(|| anyhow!("no such entry"))?.await?;
1354        let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
1355        Ok(proto::ExpandProjectEntryResponse {
1356            worktree_scan_id: scan_id as u64,
1357        })
1358    }
1359
1360    pub async fn handle_expand_all_for_entry(
1361        this: Entity<Self>,
1362        request: proto::ExpandAllForProjectEntry,
1363        mut cx: AsyncApp,
1364    ) -> Result<proto::ExpandAllForProjectEntryResponse> {
1365        let task = this.update(&mut cx, |this, cx| {
1366            this.expand_all_for_entry(ProjectEntryId::from_proto(request.entry_id), cx)
1367        })?;
1368        task.ok_or_else(|| anyhow!("no such entry"))?.await?;
1369        let scan_id = this.read_with(&cx, |this, _| this.scan_id())?;
1370        Ok(proto::ExpandAllForProjectEntryResponse {
1371            worktree_scan_id: scan_id as u64,
1372        })
1373    }
1374
1375    pub async fn handle_rename_entry(
1376        this: Entity<Self>,
1377        request: proto::RenameProjectEntry,
1378        mut cx: AsyncApp,
1379    ) -> Result<proto::ProjectEntryResponse> {
1380        let (scan_id, task) = this.update(&mut cx, |this, cx| {
1381            (
1382                this.scan_id(),
1383                this.rename_entry(
1384                    ProjectEntryId::from_proto(request.entry_id),
1385                    Arc::<Path>::from_proto(request.new_path),
1386                    cx,
1387                ),
1388            )
1389        })?;
1390        Ok(proto::ProjectEntryResponse {
1391            entry: match &task.await? {
1392                CreatedEntry::Included(entry) => Some(entry.into()),
1393                CreatedEntry::Excluded { .. } => None,
1394            },
1395            worktree_scan_id: scan_id as u64,
1396        })
1397    }
1398
1399    pub async fn handle_copy_entry(
1400        this: Entity<Self>,
1401        request: proto::CopyProjectEntry,
1402        mut cx: AsyncApp,
1403    ) -> Result<proto::ProjectEntryResponse> {
1404        let (scan_id, task) = this.update(&mut cx, |this, cx| {
1405            let relative_worktree_source_path = request
1406                .relative_worktree_source_path
1407                .map(PathBuf::from_proto);
1408            (
1409                this.scan_id(),
1410                this.copy_entry(
1411                    ProjectEntryId::from_proto(request.entry_id),
1412                    relative_worktree_source_path,
1413                    PathBuf::from_proto(request.new_path),
1414                    cx,
1415                ),
1416            )
1417        })?;
1418        Ok(proto::ProjectEntryResponse {
1419            entry: task.await?.as_ref().map(|e| e.into()),
1420            worktree_scan_id: scan_id as u64,
1421        })
1422    }
1423}
1424
1425impl LocalWorktree {
1426    pub fn fs(&self) -> &Arc<dyn Fs> {
1427        &self.fs
1428    }
1429
1430    pub fn is_path_private(&self, path: &Path) -> bool {
1431        !self.share_private_files && self.settings.is_path_private(path)
1432    }
1433
1434    fn restart_background_scanners(&mut self, cx: &Context<Worktree>) {
1435        let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
1436        let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
1437        self.scan_requests_tx = scan_requests_tx;
1438        self.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
1439
1440        self.start_background_scanner(scan_requests_rx, path_prefixes_to_scan_rx, cx);
1441        let always_included_entries = mem::take(&mut self.snapshot.always_included_entries);
1442        log::debug!(
1443            "refreshing entries for the following always included paths: {:?}",
1444            always_included_entries
1445        );
1446
1447        // Cleans up old always included entries to ensure they get updated properly. Otherwise,
1448        // nested always included entries may not get updated and will result in out-of-date info.
1449        self.refresh_entries_for_paths(always_included_entries);
1450    }
1451
1452    fn start_background_scanner(
1453        &mut self,
1454        scan_requests_rx: channel::Receiver<ScanRequest>,
1455        path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
1456        cx: &Context<Worktree>,
1457    ) {
1458        let snapshot = self.snapshot();
1459        let share_private_files = self.share_private_files;
1460        let next_entry_id = self.next_entry_id.clone();
1461        let fs = self.fs.clone();
1462        let git_hosting_provider_registry = GitHostingProviderRegistry::try_global(cx);
1463        let settings = self.settings.clone();
1464        let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
1465        let background_scanner = cx.background_spawn({
1466            let abs_path = snapshot.abs_path.as_path().to_path_buf();
1467            let background = cx.background_executor().clone();
1468            async move {
1469                let (events, watcher) = fs.watch(&abs_path, FS_WATCH_LATENCY).await;
1470                let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
1471                    log::error!("Failed to determine whether filesystem is case sensitive: {e:#}");
1472                    true
1473                });
1474
1475                let mut scanner = BackgroundScanner {
1476                    fs,
1477                    fs_case_sensitive,
1478                    status_updates_tx: scan_states_tx,
1479                    executor: background,
1480                    scan_requests_rx,
1481                    path_prefixes_to_scan_rx,
1482                    next_entry_id,
1483                    state: Arc::new(Mutex::new(BackgroundScannerState {
1484                        prev_snapshot: snapshot.snapshot.clone(),
1485                        snapshot,
1486                        scanned_dirs: Default::default(),
1487                        path_prefixes_to_scan: Default::default(),
1488                        paths_to_scan: Default::default(),
1489                        removed_entries: Default::default(),
1490                        changed_paths: Default::default(),
1491                        repository_scans: HashMap::default(),
1492                        git_hosting_provider_registry,
1493                    })),
1494                    phase: BackgroundScannerPhase::InitialScan,
1495                    share_private_files,
1496                    settings,
1497                    watcher,
1498                };
1499
1500                scanner
1501                    .run(Box::pin(
1502                        events.map(|events| events.into_iter().map(Into::into).collect()),
1503                    ))
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<'a> fmt::Debug for EntriesByPath<'a> {
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<'a> fmt::Debug for EntriesById<'a> {
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 let Ok(ignore) =
4297                    build_gitignore(&ancestor.join(*GITIGNORE), self.fs.as_ref()).await
4298                {
4299                    self.state
4300                        .lock()
4301                        .snapshot
4302                        .ignores_by_parent_abs_path
4303                        .insert(ancestor.into(), (ignore.into(), false));
4304                }
4305            }
4306
4307            let ancestor_dot_git = ancestor.join(*DOT_GIT);
4308            // Check whether the directory or file called `.git` exists (in the
4309            // case of worktrees it's a file.)
4310            if self
4311                .fs
4312                .metadata(&ancestor_dot_git)
4313                .await
4314                .is_ok_and(|metadata| metadata.is_some())
4315            {
4316                if index != 0 {
4317                    // We canonicalize, since the FS events use the canonicalized path.
4318                    if let Some(ancestor_dot_git) =
4319                        self.fs.canonicalize(&ancestor_dot_git).await.log_err()
4320                    {
4321                        // We associate the external git repo with our root folder and
4322                        // also mark where in the git repo the root folder is located.
4323                        let local_repository = self.state.lock().insert_git_repository_for_path(
4324                            WorkDirectory::AboveProject {
4325                                absolute_path: ancestor.into(),
4326                                location_in_repo: root_abs_path
4327                                    .as_path()
4328                                    .strip_prefix(ancestor)
4329                                    .unwrap()
4330                                    .into(),
4331                            },
4332                            ancestor_dot_git.clone().into(),
4333                            self.fs.as_ref(),
4334                            self.watcher.as_ref(),
4335                        );
4336
4337                        if local_repository.is_some() {
4338                            containing_git_repository = Some(ancestor_dot_git)
4339                        }
4340                    };
4341                }
4342
4343                // Reached root of git repository.
4344                break;
4345            }
4346        }
4347
4348        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4349        {
4350            let mut state = self.state.lock();
4351            state.snapshot.scan_id += 1;
4352            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
4353                let ignore_stack = state
4354                    .snapshot
4355                    .ignore_stack_for_abs_path(root_abs_path.as_path(), true);
4356                if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
4357                    root_entry.is_ignored = true;
4358                    state.insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4359                }
4360                state.enqueue_scan_dir(root_abs_path.into(), &root_entry, &scan_job_tx);
4361            }
4362        };
4363
4364        // Perform an initial scan of the directory.
4365        drop(scan_job_tx);
4366        let scans_running = self.scan_dirs(true, scan_job_rx).await;
4367        {
4368            let mut state = self.state.lock();
4369            state.snapshot.completed_scan_id = state.snapshot.scan_id;
4370        }
4371
4372        let scanning = scans_running.status_scans.load(atomic::Ordering::Acquire) > 0;
4373        self.send_status_update(scanning, SmallVec::new());
4374
4375        // Process any any FS events that occurred while performing the initial scan.
4376        // For these events, update events cannot be as precise, because we didn't
4377        // have the previous state loaded yet.
4378        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
4379        if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
4380            while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4381                paths.extend(more_paths);
4382            }
4383            self.process_events(paths.into_iter().map(Into::into).collect())
4384                .await;
4385        }
4386        if let Some(abs_path) = containing_git_repository {
4387            self.process_events(vec![abs_path]).await;
4388        }
4389
4390        // Continue processing events until the worktree is dropped.
4391        self.phase = BackgroundScannerPhase::Events;
4392
4393        loop {
4394            select_biased! {
4395                // Process any path refresh requests from the worktree. Prioritize
4396                // these before handling changes reported by the filesystem.
4397                request = self.next_scan_request().fuse() => {
4398                    let Ok(request) = request else { break };
4399                    let scanning = scans_running.status_scans.load(atomic::Ordering::Acquire) > 0;
4400                    if !self.process_scan_request(request, scanning).await {
4401                        return;
4402                    }
4403                }
4404
4405                path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
4406                    let Ok(request) = path_prefix_request else { break };
4407                    log::trace!("adding path prefix {:?}", request.path);
4408
4409                    let did_scan = self.forcibly_load_paths(&[request.path.clone()]).await;
4410                    if did_scan {
4411                        let abs_path =
4412                        {
4413                            let mut state = self.state.lock();
4414                            state.path_prefixes_to_scan.insert(request.path.clone());
4415                            state.snapshot.abs_path.as_path().join(&request.path)
4416                        };
4417
4418                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
4419                            self.process_events(vec![abs_path]).await;
4420                        }
4421                    }
4422                    let scanning = scans_running.status_scans.load(atomic::Ordering::Acquire) > 0;
4423                    self.send_status_update(scanning, request.done);
4424                }
4425
4426                paths = fs_events_rx.next().fuse() => {
4427                    let Some(mut paths) = paths else { break };
4428                    while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4429                        paths.extend(more_paths);
4430                    }
4431                    self.process_events(paths.into_iter().map(Into::into).collect()).await;
4432                }
4433            }
4434        }
4435    }
4436
4437    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
4438        log::debug!("rescanning paths {:?}", request.relative_paths);
4439
4440        request.relative_paths.sort_unstable();
4441        self.forcibly_load_paths(&request.relative_paths).await;
4442
4443        let root_path = self.state.lock().snapshot.abs_path.clone();
4444        let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
4445            Ok(path) => SanitizedPath::from(path),
4446            Err(err) => {
4447                log::error!("failed to canonicalize root path: {}", err);
4448                return true;
4449            }
4450        };
4451        let abs_paths = request
4452            .relative_paths
4453            .iter()
4454            .map(|path| {
4455                if path.file_name().is_some() {
4456                    root_canonical_path.as_path().join(path).to_path_buf()
4457                } else {
4458                    root_canonical_path.as_path().to_path_buf()
4459                }
4460            })
4461            .collect::<Vec<_>>();
4462
4463        {
4464            let mut state = self.state.lock();
4465            let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
4466            state.snapshot.scan_id += 1;
4467            if is_idle {
4468                state.snapshot.completed_scan_id = state.snapshot.scan_id;
4469            }
4470        }
4471
4472        self.reload_entries_for_paths(
4473            root_path,
4474            root_canonical_path,
4475            &request.relative_paths,
4476            abs_paths,
4477            None,
4478        )
4479        .await;
4480
4481        self.send_status_update(scanning, request.done)
4482    }
4483
4484    async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
4485        let root_path = self.state.lock().snapshot.abs_path.clone();
4486        let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
4487            Ok(path) => SanitizedPath::from(path),
4488            Err(err) => {
4489                let new_path = self
4490                    .state
4491                    .lock()
4492                    .snapshot
4493                    .root_file_handle
4494                    .clone()
4495                    .and_then(|handle| handle.current_path(&self.fs).log_err())
4496                    .map(SanitizedPath::from)
4497                    .filter(|new_path| *new_path != root_path);
4498
4499                if let Some(new_path) = new_path.as_ref() {
4500                    log::info!(
4501                        "root renamed from {} to {}",
4502                        root_path.as_path().display(),
4503                        new_path.as_path().display()
4504                    )
4505                } else {
4506                    log::warn!("root path could not be canonicalized: {}", err);
4507                }
4508                self.status_updates_tx
4509                    .unbounded_send(ScanState::RootUpdated { new_path })
4510                    .ok();
4511                return;
4512            }
4513        };
4514
4515        // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
4516        // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
4517        let skipped_files_in_dot_git = HashSet::from_iter([*COMMIT_MESSAGE, *INDEX_LOCK]);
4518        let skipped_dirs_in_dot_git = [*FSMONITOR_DAEMON];
4519
4520        let mut relative_paths = Vec::with_capacity(abs_paths.len());
4521        let mut dot_git_abs_paths = Vec::new();
4522        abs_paths.sort_unstable();
4523        abs_paths.dedup_by(|a, b| a.starts_with(b));
4524        abs_paths.retain(|abs_path| {
4525            let abs_path = SanitizedPath::from(abs_path);
4526
4527            let snapshot = &self.state.lock().snapshot;
4528            {
4529                let mut is_git_related = false;
4530
4531                let dot_git_paths = abs_path.as_path().ancestors().find_map(|ancestor| {
4532                    if smol::block_on(is_git_dir(ancestor, self.fs.as_ref())) {
4533                        let path_in_git_dir = abs_path.as_path().strip_prefix(ancestor).expect("stripping off the ancestor");
4534                        Some((ancestor.to_owned(), path_in_git_dir.to_owned()))
4535                    } else {
4536                        None
4537                    }
4538                });
4539
4540                if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
4541                    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)) {
4542                        log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");
4543                        return false;
4544                    }
4545
4546                    is_git_related = true;
4547                    if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4548                        dot_git_abs_paths.push(dot_git_abs_path);
4549                    }
4550                }
4551
4552                let relative_path: Arc<Path> =
4553                    if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
4554                        path.into()
4555                    } else {
4556                        if is_git_related {
4557                            log::debug!(
4558                              "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4559                            );
4560                        } else {
4561                            log::error!(
4562                              "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4563                            );
4564                        }
4565                        return false;
4566                    };
4567
4568                if abs_path.0.file_name() == Some(*GITIGNORE) {
4569                    for (_, repo) in snapshot.git_repositories.iter().filter(|(_, repo)| repo.directory_contains(&relative_path)) {
4570                        if !dot_git_abs_paths.iter().any(|dot_git_abs_path| dot_git_abs_path == repo.dot_git_dir_abs_path.as_ref()) {
4571                            dot_git_abs_paths.push(repo.dot_git_dir_abs_path.to_path_buf());
4572                        }
4573                    }
4574                }
4575
4576                let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
4577                    snapshot
4578                        .entry_for_path(parent)
4579                        .map_or(false, |entry| entry.kind == EntryKind::Dir)
4580                });
4581                if !parent_dir_is_loaded {
4582                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
4583                    return false;
4584                }
4585
4586                if self.settings.is_path_excluded(&relative_path) {
4587                    if !is_git_related {
4588                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
4589                    }
4590                    return false;
4591                }
4592
4593                relative_paths.push(relative_path);
4594                true
4595            }
4596        });
4597
4598        if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4599            return;
4600        }
4601
4602        self.state.lock().snapshot.scan_id += 1;
4603
4604        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4605        log::debug!("received fs events {:?}", relative_paths);
4606        self.reload_entries_for_paths(
4607            root_path,
4608            root_canonical_path,
4609            &relative_paths,
4610            abs_paths,
4611            Some(scan_job_tx.clone()),
4612        )
4613        .await;
4614
4615        self.update_ignore_statuses(scan_job_tx).await;
4616        let scans_running = self.scan_dirs(false, scan_job_rx).await;
4617
4618        let status_update = if !dot_git_abs_paths.is_empty() {
4619            Some(self.update_git_repositories(dot_git_abs_paths))
4620        } else {
4621            None
4622        };
4623
4624        let phase = self.phase;
4625        let status_update_tx = self.status_updates_tx.clone();
4626        let state = self.state.clone();
4627        self.executor
4628            .spawn(async move {
4629                if let Some(status_update) = status_update {
4630                    status_update.await;
4631                }
4632
4633                {
4634                    let mut state = state.lock();
4635                    state.snapshot.completed_scan_id = state.snapshot.scan_id;
4636                    for (_, entry) in mem::take(&mut state.removed_entries) {
4637                        state.scanned_dirs.remove(&entry.id);
4638                    }
4639                    #[cfg(test)]
4640                    state.snapshot.check_git_invariants();
4641                }
4642                let scanning = scans_running.status_scans.load(atomic::Ordering::Acquire) > 0;
4643                send_status_update_inner(phase, state, status_update_tx, scanning, SmallVec::new());
4644            })
4645            .detach();
4646    }
4647
4648    async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
4649        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4650        {
4651            let mut state = self.state.lock();
4652            let root_path = state.snapshot.abs_path.clone();
4653            for path in paths {
4654                for ancestor in path.ancestors() {
4655                    if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
4656                        if entry.kind == EntryKind::UnloadedDir {
4657                            let abs_path = root_path.as_path().join(ancestor);
4658                            state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
4659                            state.paths_to_scan.insert(path.clone());
4660                            break;
4661                        }
4662                    }
4663                }
4664            }
4665            drop(scan_job_tx);
4666        }
4667        let scans_running = Arc::new(AtomicU32::new(0));
4668        while let Ok(job) = scan_job_rx.recv().await {
4669            self.scan_dir(&scans_running, &job).await.log_err();
4670        }
4671
4672        !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
4673    }
4674
4675    async fn scan_dirs(
4676        &self,
4677        enable_progress_updates: bool,
4678        scan_jobs_rx: channel::Receiver<ScanJob>,
4679    ) -> FsScanned {
4680        if self
4681            .status_updates_tx
4682            .unbounded_send(ScanState::Started)
4683            .is_err()
4684        {
4685            return FsScanned::default();
4686        }
4687
4688        let scans_running = Arc::new(AtomicU32::new(1));
4689        let progress_update_count = AtomicUsize::new(0);
4690        self.executor
4691            .scoped(|scope| {
4692                for _ in 0..self.executor.num_cpus() {
4693                    scope.spawn(async {
4694                        let mut last_progress_update_count = 0;
4695                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4696                        futures::pin_mut!(progress_update_timer);
4697
4698                        loop {
4699                            select_biased! {
4700                                // Process any path refresh requests before moving on to process
4701                                // the scan queue, so that user operations are prioritized.
4702                                request = self.next_scan_request().fuse() => {
4703                                    let Ok(request) = request else { break };
4704                                    if !self.process_scan_request(request, true).await {
4705                                        return;
4706                                    }
4707                                }
4708
4709                                // Send periodic progress updates to the worktree. Use an atomic counter
4710                                // to ensure that only one of the workers sends a progress update after
4711                                // the update interval elapses.
4712                                _ = progress_update_timer => {
4713                                    match progress_update_count.compare_exchange(
4714                                        last_progress_update_count,
4715                                        last_progress_update_count + 1,
4716                                        SeqCst,
4717                                        SeqCst
4718                                    ) {
4719                                        Ok(_) => {
4720                                            last_progress_update_count += 1;
4721                                            self.send_status_update(true, SmallVec::new());
4722                                        }
4723                                        Err(count) => {
4724                                            last_progress_update_count = count;
4725                                        }
4726                                    }
4727                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4728                                }
4729
4730                                // Recursively load directories from the file system.
4731                                job = scan_jobs_rx.recv().fuse() => {
4732                                    let Ok(job) = job else { break };
4733                                    if let Err(err) = self.scan_dir(&scans_running, &job).await {
4734                                        if job.path.as_ref() != Path::new("") {
4735                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4736                                        }
4737                                    }
4738                                }
4739                            }
4740                        }
4741                    });
4742                }
4743            })
4744            .await;
4745
4746        scans_running.fetch_sub(1, atomic::Ordering::Release);
4747        FsScanned {
4748            status_scans: scans_running,
4749        }
4750    }
4751
4752    fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
4753        send_status_update_inner(
4754            self.phase,
4755            self.state.clone(),
4756            self.status_updates_tx.clone(),
4757            scanning,
4758            barrier,
4759        )
4760    }
4761
4762    async fn scan_dir(&self, scans_running: &Arc<AtomicU32>, job: &ScanJob) -> Result<()> {
4763        let root_abs_path;
4764        let root_char_bag;
4765        {
4766            let snapshot = &self.state.lock().snapshot;
4767            if self.settings.is_path_excluded(&job.path) {
4768                log::error!("skipping excluded directory {:?}", job.path);
4769                return Ok(());
4770            }
4771            log::debug!("scanning directory {:?}", job.path);
4772            root_abs_path = snapshot.abs_path().clone();
4773            root_char_bag = snapshot.root_char_bag;
4774        }
4775
4776        let next_entry_id = self.next_entry_id.clone();
4777        let mut ignore_stack = job.ignore_stack.clone();
4778        let mut new_ignore = None;
4779        let mut root_canonical_path = None;
4780        let mut new_entries: Vec<Entry> = Vec::new();
4781        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4782        let mut child_paths = self
4783            .fs
4784            .read_dir(&job.abs_path)
4785            .await?
4786            .filter_map(|entry| async {
4787                match entry {
4788                    Ok(entry) => Some(entry),
4789                    Err(error) => {
4790                        log::error!("error processing entry {:?}", error);
4791                        None
4792                    }
4793                }
4794            })
4795            .collect::<Vec<_>>()
4796            .await;
4797
4798        // Ensure that .git and .gitignore are processed first.
4799        swap_to_front(&mut child_paths, *GITIGNORE);
4800        swap_to_front(&mut child_paths, *DOT_GIT);
4801
4802        let mut git_status_update_jobs = Vec::new();
4803        for child_abs_path in child_paths {
4804            let child_abs_path: Arc<Path> = child_abs_path.into();
4805            let child_name = child_abs_path.file_name().unwrap();
4806            let child_path: Arc<Path> = job.path.join(child_name).into();
4807
4808            if child_name == *DOT_GIT {
4809                {
4810                    let mut state = self.state.lock();
4811                    let repo = state.insert_git_repository(
4812                        child_path.clone(),
4813                        self.fs.as_ref(),
4814                        self.watcher.as_ref(),
4815                    );
4816                    if let Some(local_repo) = repo {
4817                        scans_running.fetch_add(1, atomic::Ordering::Release);
4818                        git_status_update_jobs
4819                            .push(self.schedule_git_statuses_update(&mut state, local_repo));
4820                    }
4821                }
4822            } else if child_name == *GITIGNORE {
4823                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4824                    Ok(ignore) => {
4825                        let ignore = Arc::new(ignore);
4826                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4827                        new_ignore = Some(ignore);
4828                    }
4829                    Err(error) => {
4830                        log::error!(
4831                            "error loading .gitignore file {:?} - {:?}",
4832                            child_name,
4833                            error
4834                        );
4835                    }
4836                }
4837            }
4838
4839            if self.settings.is_path_excluded(&child_path) {
4840                log::debug!("skipping excluded child entry {child_path:?}");
4841                self.state.lock().remove_path(&child_path);
4842                continue;
4843            }
4844
4845            let child_metadata = match self.fs.metadata(&child_abs_path).await {
4846                Ok(Some(metadata)) => metadata,
4847                Ok(None) => continue,
4848                Err(err) => {
4849                    log::error!("error processing {child_abs_path:?}: {err:?}");
4850                    continue;
4851                }
4852            };
4853
4854            let mut child_entry = Entry::new(
4855                child_path.clone(),
4856                &child_metadata,
4857                &next_entry_id,
4858                root_char_bag,
4859                None,
4860            );
4861
4862            if job.is_external {
4863                child_entry.is_external = true;
4864            } else if child_metadata.is_symlink {
4865                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4866                    Ok(path) => path,
4867                    Err(err) => {
4868                        log::error!(
4869                            "error reading target of symlink {:?}: {:?}",
4870                            child_abs_path,
4871                            err
4872                        );
4873                        continue;
4874                    }
4875                };
4876
4877                // lazily canonicalize the root path in order to determine if
4878                // symlinks point outside of the worktree.
4879                let root_canonical_path = match &root_canonical_path {
4880                    Some(path) => path,
4881                    None => match self.fs.canonicalize(&root_abs_path).await {
4882                        Ok(path) => root_canonical_path.insert(path),
4883                        Err(err) => {
4884                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4885                            continue;
4886                        }
4887                    },
4888                };
4889
4890                if !canonical_path.starts_with(root_canonical_path) {
4891                    child_entry.is_external = true;
4892                }
4893
4894                child_entry.canonical_path = Some(canonical_path.into());
4895            }
4896
4897            if child_entry.is_dir() {
4898                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4899                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4900
4901                // Avoid recursing until crash in the case of a recursive symlink
4902                if job.ancestor_inodes.contains(&child_entry.inode) {
4903                    new_jobs.push(None);
4904                } else {
4905                    let mut ancestor_inodes = job.ancestor_inodes.clone();
4906                    ancestor_inodes.insert(child_entry.inode);
4907
4908                    new_jobs.push(Some(ScanJob {
4909                        abs_path: child_abs_path.clone(),
4910                        path: child_path,
4911                        is_external: child_entry.is_external,
4912                        ignore_stack: if child_entry.is_ignored {
4913                            IgnoreStack::all()
4914                        } else {
4915                            ignore_stack.clone()
4916                        },
4917                        ancestor_inodes,
4918                        scan_queue: job.scan_queue.clone(),
4919                    }));
4920                }
4921            } else {
4922                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4923                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4924            }
4925
4926            {
4927                let relative_path = job.path.join(child_name);
4928                if self.is_path_private(&relative_path) {
4929                    log::debug!("detected private file: {relative_path:?}");
4930                    child_entry.is_private = true;
4931                }
4932            }
4933
4934            new_entries.push(child_entry);
4935        }
4936
4937        let task_state = self.state.clone();
4938        let phase = self.phase;
4939        let status_updates_tx = self.status_updates_tx.clone();
4940        let scans_running = scans_running.clone();
4941        self.executor
4942            .spawn(async move {
4943                if !git_status_update_jobs.is_empty() {
4944                    let status_updates = join_all(git_status_update_jobs).await;
4945                    let status_updated = status_updates
4946                        .iter()
4947                        .any(|update_result| update_result.is_ok());
4948                    scans_running.fetch_sub(status_updates.len() as u32, atomic::Ordering::Release);
4949                    if status_updated {
4950                        let scanning = scans_running.load(atomic::Ordering::Acquire) > 0;
4951                        send_status_update_inner(
4952                            phase,
4953                            task_state,
4954                            status_updates_tx,
4955                            scanning,
4956                            SmallVec::new(),
4957                        );
4958                    }
4959                }
4960            })
4961            .detach();
4962
4963        let mut state = self.state.lock();
4964
4965        // Identify any subdirectories that should not be scanned.
4966        let mut job_ix = 0;
4967        for entry in &mut new_entries {
4968            state.reuse_entry_id(entry);
4969            if entry.is_dir() {
4970                if state.should_scan_directory(entry) {
4971                    job_ix += 1;
4972                } else {
4973                    log::debug!("defer scanning directory {:?}", entry.path);
4974                    entry.kind = EntryKind::UnloadedDir;
4975                    new_jobs.remove(job_ix);
4976                }
4977            }
4978            if entry.is_always_included {
4979                state
4980                    .snapshot
4981                    .always_included_entries
4982                    .push(entry.path.clone());
4983            }
4984        }
4985
4986        state.populate_dir(&job.path, new_entries, new_ignore);
4987        self.watcher.add(job.abs_path.as_ref()).log_err();
4988
4989        for new_job in new_jobs.into_iter().flatten() {
4990            job.scan_queue
4991                .try_send(new_job)
4992                .expect("channel is unbounded");
4993        }
4994
4995        Ok(())
4996    }
4997
4998    /// All list arguments should be sorted before calling this function
4999    async fn reload_entries_for_paths(
5000        &self,
5001        root_abs_path: SanitizedPath,
5002        root_canonical_path: SanitizedPath,
5003        relative_paths: &[Arc<Path>],
5004        abs_paths: Vec<PathBuf>,
5005        scan_queue_tx: Option<Sender<ScanJob>>,
5006    ) {
5007        // grab metadata for all requested paths
5008        let metadata = futures::future::join_all(
5009            abs_paths
5010                .iter()
5011                .map(|abs_path| async move {
5012                    let metadata = self.fs.metadata(abs_path).await?;
5013                    if let Some(metadata) = metadata {
5014                        let canonical_path = self.fs.canonicalize(abs_path).await?;
5015
5016                        // If we're on a case-insensitive filesystem (default on macOS), we want
5017                        // to only ignore metadata for non-symlink files if their absolute-path matches
5018                        // the canonical-path.
5019                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
5020                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
5021                        // treated as removed.
5022                        if !self.fs_case_sensitive && !metadata.is_symlink {
5023                            let canonical_file_name = canonical_path.file_name();
5024                            let file_name = abs_path.file_name();
5025                            if canonical_file_name != file_name {
5026                                return Ok(None);
5027                            }
5028                        }
5029
5030                        anyhow::Ok(Some((metadata, SanitizedPath::from(canonical_path))))
5031                    } else {
5032                        Ok(None)
5033                    }
5034                })
5035                .collect::<Vec<_>>(),
5036        )
5037        .await;
5038
5039        let mut state = self.state.lock();
5040        let doing_recursive_update = scan_queue_tx.is_some();
5041
5042        // Remove any entries for paths that no longer exist or are being recursively
5043        // refreshed. Do this before adding any new entries, so that renames can be
5044        // detected regardless of the order of the paths.
5045        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
5046            if matches!(metadata, Ok(None)) || doing_recursive_update {
5047                log::trace!("remove path {:?}", path);
5048                state.remove_path(path);
5049            }
5050        }
5051
5052        // Group all relative paths by their git repository.
5053        let mut paths_by_git_repo = HashMap::default();
5054        for relative_path in relative_paths.iter() {
5055            let repository_data = state
5056                .snapshot
5057                .local_repo_for_path(relative_path)
5058                .zip(state.snapshot.repository_for_path(relative_path));
5059            if let Some((local_repo, entry)) = repository_data {
5060                if let Ok(repo_path) = local_repo.relativize(relative_path) {
5061                    paths_by_git_repo
5062                        .entry(local_repo.work_directory.clone())
5063                        .or_insert_with(|| RepoPaths {
5064                            entry: entry.clone(),
5065                            repo: local_repo.repo_ptr.clone(),
5066                            repo_paths: Default::default(),
5067                        })
5068                        .add_path(repo_path);
5069                }
5070            }
5071        }
5072
5073        for (work_directory, mut paths) in paths_by_git_repo {
5074            if let Ok(status) = paths.repo.status(&paths.repo_paths) {
5075                let mut changed_path_statuses = Vec::new();
5076                let statuses = paths.entry.statuses_by_path.clone();
5077                let mut cursor = statuses.cursor::<PathProgress>(&());
5078
5079                for (repo_path, status) in &*status.entries {
5080                    paths.remove_repo_path(repo_path);
5081                    if cursor.seek_forward(&PathTarget::Path(repo_path), Bias::Left, &()) {
5082                        if &cursor.item().unwrap().status == status {
5083                            continue;
5084                        }
5085                    }
5086
5087                    changed_path_statuses.push(Edit::Insert(StatusEntry {
5088                        repo_path: repo_path.clone(),
5089                        status: *status,
5090                    }));
5091                }
5092
5093                let mut cursor = statuses.cursor::<PathProgress>(&());
5094                for path in paths.repo_paths {
5095                    if cursor.seek_forward(&PathTarget::Path(&path), Bias::Left, &()) {
5096                        changed_path_statuses.push(Edit::Remove(PathKey(path.0)));
5097                    }
5098                }
5099
5100                if !changed_path_statuses.is_empty() {
5101                    let work_directory_id = state.snapshot.repositories.update(
5102                        &work_directory.path_key(),
5103                        &(),
5104                        move |repository_entry| {
5105                            repository_entry
5106                                .statuses_by_path
5107                                .edit(changed_path_statuses, &());
5108
5109                            repository_entry.work_directory_id
5110                        },
5111                    );
5112
5113                    if let Some(work_directory_id) = work_directory_id {
5114                        let scan_id = state.snapshot.scan_id;
5115                        state.snapshot.git_repositories.update(
5116                            &work_directory_id,
5117                            |local_repository_entry| {
5118                                local_repository_entry.status_scan_id = scan_id;
5119                            },
5120                        );
5121                    }
5122                }
5123            }
5124        }
5125
5126        for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
5127            let abs_path: Arc<Path> = root_abs_path.as_path().join(path).into();
5128            match metadata {
5129                Ok(Some((metadata, canonical_path))) => {
5130                    let ignore_stack = state
5131                        .snapshot
5132                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
5133                    let is_external = !canonical_path.starts_with(&root_canonical_path);
5134                    let mut fs_entry = Entry::new(
5135                        path.clone(),
5136                        &metadata,
5137                        self.next_entry_id.as_ref(),
5138                        state.snapshot.root_char_bag,
5139                        if metadata.is_symlink {
5140                            Some(canonical_path.as_path().to_path_buf().into())
5141                        } else {
5142                            None
5143                        },
5144                    );
5145
5146                    let is_dir = fs_entry.is_dir();
5147                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
5148                    fs_entry.is_external = is_external;
5149                    fs_entry.is_private = self.is_path_private(path);
5150                    fs_entry.is_always_included = self.settings.is_path_always_included(path);
5151
5152                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
5153                        if state.should_scan_directory(&fs_entry)
5154                            || (fs_entry.path.as_os_str().is_empty()
5155                                && abs_path.file_name() == Some(*DOT_GIT))
5156                        {
5157                            state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
5158                        } else {
5159                            fs_entry.kind = EntryKind::UnloadedDir;
5160                        }
5161                    }
5162
5163                    state.insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
5164                }
5165                Ok(None) => {
5166                    self.remove_repo_path(path, &mut state.snapshot);
5167                }
5168                Err(err) => {
5169                    log::error!("error reading file {abs_path:?} on event: {err:#}");
5170                }
5171            }
5172        }
5173
5174        util::extend_sorted(
5175            &mut state.changed_paths,
5176            relative_paths.iter().cloned(),
5177            usize::MAX,
5178            Ord::cmp,
5179        );
5180    }
5181
5182    fn remove_repo_path(&self, path: &Arc<Path>, snapshot: &mut LocalSnapshot) -> Option<()> {
5183        if !path
5184            .components()
5185            .any(|component| component.as_os_str() == *DOT_GIT)
5186        {
5187            if let Some(repository) = snapshot.repository(PathKey(path.clone())) {
5188                snapshot
5189                    .git_repositories
5190                    .remove(&repository.work_directory_id);
5191                snapshot
5192                    .snapshot
5193                    .repositories
5194                    .remove(&repository.work_directory.path_key(), &());
5195                return Some(());
5196            }
5197        }
5198
5199        Some(())
5200    }
5201
5202    async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
5203        let mut ignores_to_update = Vec::new();
5204        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
5205        let prev_snapshot;
5206        {
5207            let snapshot = &mut self.state.lock().snapshot;
5208            let abs_path = snapshot.abs_path.clone();
5209            snapshot
5210                .ignores_by_parent_abs_path
5211                .retain(|parent_abs_path, (_, needs_update)| {
5212                    if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path()) {
5213                        if *needs_update {
5214                            *needs_update = false;
5215                            if snapshot.snapshot.entry_for_path(parent_path).is_some() {
5216                                ignores_to_update.push(parent_abs_path.clone());
5217                            }
5218                        }
5219
5220                        let ignore_path = parent_path.join(*GITIGNORE);
5221                        if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
5222                            return false;
5223                        }
5224                    }
5225                    true
5226                });
5227
5228            ignores_to_update.sort_unstable();
5229            let mut ignores_to_update = ignores_to_update.into_iter().peekable();
5230            while let Some(parent_abs_path) = ignores_to_update.next() {
5231                while ignores_to_update
5232                    .peek()
5233                    .map_or(false, |p| p.starts_with(&parent_abs_path))
5234                {
5235                    ignores_to_update.next().unwrap();
5236                }
5237
5238                let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
5239                ignore_queue_tx
5240                    .send_blocking(UpdateIgnoreStatusJob {
5241                        abs_path: parent_abs_path,
5242                        ignore_stack,
5243                        ignore_queue: ignore_queue_tx.clone(),
5244                        scan_queue: scan_job_tx.clone(),
5245                    })
5246                    .unwrap();
5247            }
5248
5249            prev_snapshot = snapshot.clone();
5250        }
5251        drop(ignore_queue_tx);
5252
5253        self.executor
5254            .scoped(|scope| {
5255                for _ in 0..self.executor.num_cpus() {
5256                    scope.spawn(async {
5257                        loop {
5258                            select_biased! {
5259                                // Process any path refresh requests before moving on to process
5260                                // the queue of ignore statuses.
5261                                request = self.next_scan_request().fuse() => {
5262                                    let Ok(request) = request else { break };
5263                                    if !self.process_scan_request(request, true).await {
5264                                        return;
5265                                    }
5266                                }
5267
5268                                // Recursively process directories whose ignores have changed.
5269                                job = ignore_queue_rx.recv().fuse() => {
5270                                    let Ok(job) = job else { break };
5271                                    self.update_ignore_status(job, &prev_snapshot).await;
5272                                }
5273                            }
5274                        }
5275                    });
5276                }
5277            })
5278            .await;
5279    }
5280
5281    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
5282        log::trace!("update ignore status {:?}", job.abs_path);
5283
5284        let mut ignore_stack = job.ignore_stack;
5285        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
5286            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
5287        }
5288
5289        let mut entries_by_id_edits = Vec::new();
5290        let mut entries_by_path_edits = Vec::new();
5291        let path = job
5292            .abs_path
5293            .strip_prefix(snapshot.abs_path.as_path())
5294            .unwrap();
5295
5296        for mut entry in snapshot.child_entries(path).cloned() {
5297            let was_ignored = entry.is_ignored;
5298            let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
5299            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
5300
5301            if entry.is_dir() {
5302                let child_ignore_stack = if entry.is_ignored {
5303                    IgnoreStack::all()
5304                } else {
5305                    ignore_stack.clone()
5306                };
5307
5308                // Scan any directories that were previously ignored and weren't previously scanned.
5309                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
5310                    let state = self.state.lock();
5311                    if state.should_scan_directory(&entry) {
5312                        state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
5313                    }
5314                }
5315
5316                job.ignore_queue
5317                    .send(UpdateIgnoreStatusJob {
5318                        abs_path: abs_path.clone(),
5319                        ignore_stack: child_ignore_stack,
5320                        ignore_queue: job.ignore_queue.clone(),
5321                        scan_queue: job.scan_queue.clone(),
5322                    })
5323                    .await
5324                    .unwrap();
5325            }
5326
5327            if entry.is_ignored != was_ignored {
5328                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
5329                path_entry.scan_id = snapshot.scan_id;
5330                path_entry.is_ignored = entry.is_ignored;
5331                entries_by_id_edits.push(Edit::Insert(path_entry));
5332                entries_by_path_edits.push(Edit::Insert(entry));
5333            }
5334        }
5335
5336        let state = &mut self.state.lock();
5337        for edit in &entries_by_path_edits {
5338            if let Edit::Insert(entry) = edit {
5339                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
5340                    state.changed_paths.insert(ix, entry.path.clone());
5341                }
5342            }
5343        }
5344
5345        state
5346            .snapshot
5347            .entries_by_path
5348            .edit(entries_by_path_edits, &());
5349        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
5350    }
5351
5352    fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Task<()> {
5353        log::debug!("reloading repositories: {dot_git_paths:?}");
5354
5355        let mut status_updates = Vec::new();
5356        {
5357            let mut state = self.state.lock();
5358            let scan_id = state.snapshot.scan_id;
5359            for dot_git_dir in dot_git_paths {
5360                let existing_repository_entry =
5361                    state
5362                        .snapshot
5363                        .git_repositories
5364                        .iter()
5365                        .find_map(|(_, repo)| {
5366                            if repo.dot_git_dir_abs_path.as_ref() == &dot_git_dir
5367                                || repo.dot_git_worktree_abs_path.as_deref() == Some(&dot_git_dir)
5368                            {
5369                                Some(repo.clone())
5370                            } else {
5371                                None
5372                            }
5373                        });
5374
5375                let local_repository = match existing_repository_entry {
5376                    None => {
5377                        let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path())
5378                        else {
5379                            return Task::ready(());
5380                        };
5381                        match state.insert_git_repository(
5382                            relative.into(),
5383                            self.fs.as_ref(),
5384                            self.watcher.as_ref(),
5385                        ) {
5386                            Some(output) => output,
5387                            None => continue,
5388                        }
5389                    }
5390                    Some(local_repository) => {
5391                        if local_repository.git_dir_scan_id == scan_id {
5392                            continue;
5393                        }
5394                        local_repository.repo_ptr.reload_index();
5395
5396                        state.snapshot.git_repositories.update(
5397                            &local_repository.work_directory_id,
5398                            |entry| {
5399                                entry.git_dir_scan_id = scan_id;
5400                                entry.status_scan_id = scan_id;
5401                            },
5402                        );
5403
5404                        local_repository
5405                    }
5406                };
5407
5408                status_updates
5409                    .push(self.schedule_git_statuses_update(&mut state, local_repository));
5410            }
5411
5412            // Remove any git repositories whose .git entry no longer exists.
5413            let snapshot = &mut state.snapshot;
5414            let mut ids_to_preserve = HashSet::default();
5415            for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
5416                let exists_in_snapshot = snapshot
5417                    .entry_for_id(work_directory_id)
5418                    .map_or(false, |entry| {
5419                        snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
5420                    });
5421
5422                if exists_in_snapshot
5423                    || matches!(
5424                        smol::block_on(self.fs.metadata(&entry.dot_git_dir_abs_path)),
5425                        Ok(Some(_))
5426                    )
5427                {
5428                    ids_to_preserve.insert(work_directory_id);
5429                }
5430            }
5431
5432            snapshot
5433                .git_repositories
5434                .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
5435            snapshot.repositories.retain(&(), |entry| {
5436                ids_to_preserve.contains(&entry.work_directory_id)
5437            });
5438        }
5439
5440        self.executor.spawn(async move {
5441            let _updates_finished: Vec<Result<(), oneshot::Canceled>> =
5442                join_all(status_updates).await;
5443        })
5444    }
5445
5446    /// Update the git statuses for a given batch of entries.
5447    fn schedule_git_statuses_update(
5448        &self,
5449        state: &mut BackgroundScannerState,
5450        mut local_repository: LocalRepositoryEntry,
5451    ) -> oneshot::Receiver<()> {
5452        let repository_name = local_repository.work_directory.display_name();
5453        let path_key = local_repository.work_directory.path_key();
5454
5455        let job_state = self.state.clone();
5456        let (tx, rx) = oneshot::channel();
5457
5458        state.repository_scans.insert(
5459            path_key.clone(),
5460            self.executor.spawn(async move {
5461                update_branches(&job_state, &mut local_repository).log_err();
5462                log::trace!("updating git statuses for repo {repository_name}",);
5463                let t0 = Instant::now();
5464
5465                let Some(statuses) = local_repository
5466                    .repo()
5467                    .status(&[git::WORK_DIRECTORY_REPO_PATH.clone()])
5468                    .log_err()
5469                else {
5470                    return;
5471                };
5472                log::trace!(
5473                    "computed git statuses for repo {repository_name} in {:?}",
5474                    t0.elapsed()
5475                );
5476
5477                let t0 = Instant::now();
5478                let mut changed_paths = Vec::new();
5479                let snapshot = job_state.lock().snapshot.snapshot.clone();
5480
5481                let Some(mut repository) = snapshot
5482                    .repository(path_key)
5483                    .context(
5484                        "Tried to update git statuses for a repository that isn't in the snapshot",
5485                    )
5486                    .log_err()
5487                else {
5488                    return;
5489                };
5490
5491                let merge_head_shas = local_repository.repo().merge_head_shas();
5492                if merge_head_shas != local_repository.current_merge_head_shas {
5493                    mem::take(&mut repository.current_merge_conflicts);
5494                }
5495
5496                let mut new_entries_by_path = SumTree::new(&());
5497                for (repo_path, status) in statuses.entries.iter() {
5498                    let project_path = repository.work_directory.unrelativize(repo_path);
5499
5500                    new_entries_by_path.insert_or_replace(
5501                        StatusEntry {
5502                            repo_path: repo_path.clone(),
5503                            status: *status,
5504                        },
5505                        &(),
5506                    );
5507                    if status.is_conflicted() {
5508                        repository.current_merge_conflicts.insert(repo_path.clone());
5509                    }
5510
5511                    if let Some(path) = project_path {
5512                        changed_paths.push(path);
5513                    }
5514                }
5515
5516                repository.statuses_by_path = new_entries_by_path;
5517                let mut state = job_state.lock();
5518                state
5519                    .snapshot
5520                    .repositories
5521                    .insert_or_replace(repository, &());
5522                state.snapshot.git_repositories.update(
5523                    &local_repository.work_directory_id,
5524                    |entry| {
5525                        entry.current_merge_head_shas = merge_head_shas;
5526                        entry.merge_message = std::fs::read_to_string(
5527                            local_repository.dot_git_dir_abs_path.join("MERGE_MSG"),
5528                        )
5529                        .ok()
5530                        .and_then(|merge_msg| Some(merge_msg.lines().next()?.to_owned()));
5531                        entry.status_scan_id += 1;
5532                    },
5533                );
5534
5535                util::extend_sorted(
5536                    &mut state.changed_paths,
5537                    changed_paths,
5538                    usize::MAX,
5539                    Ord::cmp,
5540                );
5541
5542                log::trace!(
5543                    "applied git status updates for repo {repository_name} in {:?}",
5544                    t0.elapsed(),
5545                );
5546                tx.send(()).ok();
5547            }),
5548        );
5549        rx
5550    }
5551
5552    async fn progress_timer(&self, running: bool) {
5553        if !running {
5554            return futures::future::pending().await;
5555        }
5556
5557        #[cfg(any(test, feature = "test-support"))]
5558        if self.fs.is_fake() {
5559            return self.executor.simulate_random_delay().await;
5560        }
5561
5562        smol::Timer::after(FS_WATCH_LATENCY).await;
5563    }
5564
5565    fn is_path_private(&self, path: &Path) -> bool {
5566        !self.share_private_files && self.settings.is_path_private(path)
5567    }
5568
5569    async fn next_scan_request(&self) -> Result<ScanRequest> {
5570        let mut request = self.scan_requests_rx.recv().await?;
5571        while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5572            request.relative_paths.extend(next_request.relative_paths);
5573            request.done.extend(next_request.done);
5574        }
5575        Ok(request)
5576    }
5577}
5578
5579fn send_status_update_inner(
5580    phase: BackgroundScannerPhase,
5581    state: Arc<Mutex<BackgroundScannerState>>,
5582    status_updates_tx: UnboundedSender<ScanState>,
5583    scanning: bool,
5584    barrier: SmallVec<[barrier::Sender; 1]>,
5585) -> bool {
5586    let mut state = state.lock();
5587    if state.changed_paths.is_empty() && scanning {
5588        return true;
5589    }
5590
5591    let new_snapshot = state.snapshot.clone();
5592    let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
5593    let changes = build_diff(phase, &old_snapshot, &new_snapshot, &state.changed_paths);
5594    state.changed_paths.clear();
5595
5596    status_updates_tx
5597        .unbounded_send(ScanState::Updated {
5598            snapshot: new_snapshot,
5599            changes,
5600            scanning,
5601            barrier,
5602        })
5603        .is_ok()
5604}
5605
5606fn update_branches(
5607    state: &Mutex<BackgroundScannerState>,
5608    repository: &mut LocalRepositoryEntry,
5609) -> Result<()> {
5610    let branches = repository.repo().branches()?;
5611    let snapshot = state.lock().snapshot.snapshot.clone();
5612    let mut repository = snapshot
5613        .repository(repository.work_directory.path_key())
5614        .context("Missing repository")?;
5615    repository.current_branch = branches.into_iter().find(|branch| branch.is_head);
5616
5617    let mut state = state.lock();
5618    state
5619        .snapshot
5620        .repositories
5621        .insert_or_replace(repository, &());
5622
5623    Ok(())
5624}
5625
5626fn build_diff(
5627    phase: BackgroundScannerPhase,
5628    old_snapshot: &Snapshot,
5629    new_snapshot: &Snapshot,
5630    event_paths: &[Arc<Path>],
5631) -> UpdatedEntriesSet {
5632    use BackgroundScannerPhase::*;
5633    use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
5634
5635    // Identify which paths have changed. Use the known set of changed
5636    // parent paths to optimize the search.
5637    let mut changes = Vec::new();
5638    let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(&());
5639    let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(&());
5640    let mut last_newly_loaded_dir_path = None;
5641    old_paths.next(&());
5642    new_paths.next(&());
5643    for path in event_paths {
5644        let path = PathKey(path.clone());
5645        if old_paths.item().map_or(false, |e| e.path < path.0) {
5646            old_paths.seek_forward(&path, Bias::Left, &());
5647        }
5648        if new_paths.item().map_or(false, |e| e.path < path.0) {
5649            new_paths.seek_forward(&path, Bias::Left, &());
5650        }
5651        loop {
5652            match (old_paths.item(), new_paths.item()) {
5653                (Some(old_entry), Some(new_entry)) => {
5654                    if old_entry.path > path.0
5655                        && new_entry.path > path.0
5656                        && !old_entry.path.starts_with(&path.0)
5657                        && !new_entry.path.starts_with(&path.0)
5658                    {
5659                        break;
5660                    }
5661
5662                    match Ord::cmp(&old_entry.path, &new_entry.path) {
5663                        Ordering::Less => {
5664                            changes.push((old_entry.path.clone(), old_entry.id, Removed));
5665                            old_paths.next(&());
5666                        }
5667                        Ordering::Equal => {
5668                            if phase == EventsReceivedDuringInitialScan {
5669                                if old_entry.id != new_entry.id {
5670                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5671                                }
5672                                // If the worktree was not fully initialized when this event was generated,
5673                                // we can't know whether this entry was added during the scan or whether
5674                                // it was merely updated.
5675                                changes.push((
5676                                    new_entry.path.clone(),
5677                                    new_entry.id,
5678                                    AddedOrUpdated,
5679                                ));
5680                            } else if old_entry.id != new_entry.id {
5681                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
5682                                changes.push((new_entry.path.clone(), new_entry.id, Added));
5683                            } else if old_entry != new_entry {
5684                                if old_entry.kind.is_unloaded() {
5685                                    last_newly_loaded_dir_path = Some(&new_entry.path);
5686                                    changes.push((new_entry.path.clone(), new_entry.id, Loaded));
5687                                } else {
5688                                    changes.push((new_entry.path.clone(), new_entry.id, Updated));
5689                                }
5690                            }
5691                            old_paths.next(&());
5692                            new_paths.next(&());
5693                        }
5694                        Ordering::Greater => {
5695                            let is_newly_loaded = phase == InitialScan
5696                                || last_newly_loaded_dir_path
5697                                    .as_ref()
5698                                    .map_or(false, |dir| new_entry.path.starts_with(dir));
5699                            changes.push((
5700                                new_entry.path.clone(),
5701                                new_entry.id,
5702                                if is_newly_loaded { Loaded } else { Added },
5703                            ));
5704                            new_paths.next(&());
5705                        }
5706                    }
5707                }
5708                (Some(old_entry), None) => {
5709                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5710                    old_paths.next(&());
5711                }
5712                (None, Some(new_entry)) => {
5713                    let is_newly_loaded = phase == InitialScan
5714                        || last_newly_loaded_dir_path
5715                            .as_ref()
5716                            .map_or(false, |dir| new_entry.path.starts_with(dir));
5717                    changes.push((
5718                        new_entry.path.clone(),
5719                        new_entry.id,
5720                        if is_newly_loaded { Loaded } else { Added },
5721                    ));
5722                    new_paths.next(&());
5723                }
5724                (None, None) => break,
5725            }
5726        }
5727    }
5728
5729    changes.into()
5730}
5731
5732fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &OsStr) {
5733    let position = child_paths
5734        .iter()
5735        .position(|path| path.file_name().unwrap() == file);
5736    if let Some(position) = position {
5737        let temp = child_paths.remove(position);
5738        child_paths.insert(0, temp);
5739    }
5740}
5741
5742fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
5743    let mut result = root_char_bag;
5744    result.extend(
5745        path.to_string_lossy()
5746            .chars()
5747            .map(|c| c.to_ascii_lowercase()),
5748    );
5749    result
5750}
5751
5752#[derive(Debug)]
5753struct RepoPaths {
5754    repo: Arc<dyn GitRepository>,
5755    entry: RepositoryEntry,
5756    // sorted
5757    repo_paths: Vec<RepoPath>,
5758}
5759
5760impl RepoPaths {
5761    fn add_path(&mut self, repo_path: RepoPath) {
5762        match self.repo_paths.binary_search(&repo_path) {
5763            Ok(_) => {}
5764            Err(ix) => self.repo_paths.insert(ix, repo_path),
5765        }
5766    }
5767
5768    fn remove_repo_path(&mut self, repo_path: &RepoPath) {
5769        match self.repo_paths.binary_search(&repo_path) {
5770            Ok(ix) => {
5771                self.repo_paths.remove(ix);
5772            }
5773            Err(_) => {}
5774        }
5775    }
5776}
5777
5778#[derive(Debug)]
5779struct ScanJob {
5780    abs_path: Arc<Path>,
5781    path: Arc<Path>,
5782    ignore_stack: Arc<IgnoreStack>,
5783    scan_queue: Sender<ScanJob>,
5784    ancestor_inodes: TreeSet<u64>,
5785    is_external: bool,
5786}
5787
5788struct UpdateIgnoreStatusJob {
5789    abs_path: Arc<Path>,
5790    ignore_stack: Arc<IgnoreStack>,
5791    ignore_queue: Sender<UpdateIgnoreStatusJob>,
5792    scan_queue: Sender<ScanJob>,
5793}
5794
5795pub trait WorktreeModelHandle {
5796    #[cfg(any(test, feature = "test-support"))]
5797    fn flush_fs_events<'a>(
5798        &self,
5799        cx: &'a mut gpui::TestAppContext,
5800    ) -> futures::future::LocalBoxFuture<'a, ()>;
5801
5802    #[cfg(any(test, feature = "test-support"))]
5803    fn flush_fs_events_in_root_git_repository<'a>(
5804        &self,
5805        cx: &'a mut gpui::TestAppContext,
5806    ) -> futures::future::LocalBoxFuture<'a, ()>;
5807}
5808
5809impl WorktreeModelHandle for Entity<Worktree> {
5810    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5811    // occurred before the worktree was constructed. These events can cause the worktree to perform
5812    // extra directory scans, and emit extra scan-state notifications.
5813    //
5814    // This function mutates the worktree's directory and waits for those mutations to be picked up,
5815    // to ensure that all redundant FS events have already been processed.
5816    #[cfg(any(test, feature = "test-support"))]
5817    fn flush_fs_events<'a>(
5818        &self,
5819        cx: &'a mut gpui::TestAppContext,
5820    ) -> futures::future::LocalBoxFuture<'a, ()> {
5821        let file_name = "fs-event-sentinel";
5822
5823        let tree = self.clone();
5824        let (fs, root_path) = self.update(cx, |tree, _| {
5825            let tree = tree.as_local().unwrap();
5826            (tree.fs.clone(), tree.abs_path().clone())
5827        });
5828
5829        async move {
5830            fs.create_file(&root_path.join(file_name), Default::default())
5831                .await
5832                .unwrap();
5833
5834            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
5835                .await;
5836
5837            fs.remove_file(&root_path.join(file_name), Default::default())
5838                .await
5839                .unwrap();
5840            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
5841                .await;
5842
5843            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5844                .await;
5845        }
5846        .boxed_local()
5847    }
5848
5849    // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5850    // the .git folder of the root repository.
5851    // The reason for its existence is that a repository's .git folder might live *outside* of the
5852    // worktree and thus its FS events might go through a different path.
5853    // In order to flush those, we need to create artificial events in the .git folder and wait
5854    // for the repository to be reloaded.
5855    #[cfg(any(test, feature = "test-support"))]
5856    fn flush_fs_events_in_root_git_repository<'a>(
5857        &self,
5858        cx: &'a mut gpui::TestAppContext,
5859    ) -> futures::future::LocalBoxFuture<'a, ()> {
5860        let file_name = "fs-event-sentinel";
5861
5862        let tree = self.clone();
5863        let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
5864            let tree = tree.as_local().unwrap();
5865            let root_entry = tree.root_git_entry().unwrap();
5866            let local_repo_entry = tree.get_local_repo(&root_entry).unwrap();
5867            (
5868                tree.fs.clone(),
5869                local_repo_entry.dot_git_dir_abs_path.clone(),
5870                local_repo_entry.git_dir_scan_id,
5871            )
5872        });
5873
5874        let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5875            let root_entry = tree.root_git_entry().unwrap();
5876            let local_repo_entry = tree
5877                .as_local()
5878                .unwrap()
5879                .get_local_repo(&root_entry)
5880                .unwrap();
5881
5882            if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5883                *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5884                true
5885            } else {
5886                false
5887            }
5888        };
5889
5890        async move {
5891            fs.create_file(&root_path.join(file_name), Default::default())
5892                .await
5893                .unwrap();
5894
5895            cx.condition(&tree, |tree, _| {
5896                scan_id_increased(tree, &mut git_dir_scan_id)
5897            })
5898            .await;
5899
5900            fs.remove_file(&root_path.join(file_name), Default::default())
5901                .await
5902                .unwrap();
5903
5904            cx.condition(&tree, |tree, _| {
5905                scan_id_increased(tree, &mut git_dir_scan_id)
5906            })
5907            .await;
5908
5909            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5910                .await;
5911        }
5912        .boxed_local()
5913    }
5914}
5915
5916#[derive(Clone, Debug)]
5917struct TraversalProgress<'a> {
5918    max_path: &'a Path,
5919    count: usize,
5920    non_ignored_count: usize,
5921    file_count: usize,
5922    non_ignored_file_count: usize,
5923}
5924
5925impl<'a> TraversalProgress<'a> {
5926    fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5927        match (include_files, include_dirs, include_ignored) {
5928            (true, true, true) => self.count,
5929            (true, true, false) => self.non_ignored_count,
5930            (true, false, true) => self.file_count,
5931            (true, false, false) => self.non_ignored_file_count,
5932            (false, true, true) => self.count - self.file_count,
5933            (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5934            (false, false, _) => 0,
5935        }
5936    }
5937}
5938
5939impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5940    fn zero(_cx: &()) -> Self {
5941        Default::default()
5942    }
5943
5944    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5945        self.max_path = summary.max_path.as_ref();
5946        self.count += summary.count;
5947        self.non_ignored_count += summary.non_ignored_count;
5948        self.file_count += summary.file_count;
5949        self.non_ignored_file_count += summary.non_ignored_file_count;
5950    }
5951}
5952
5953impl<'a> Default for TraversalProgress<'a> {
5954    fn default() -> Self {
5955        Self {
5956            max_path: Path::new(""),
5957            count: 0,
5958            non_ignored_count: 0,
5959            file_count: 0,
5960            non_ignored_file_count: 0,
5961        }
5962    }
5963}
5964
5965#[derive(Debug, Clone, Copy)]
5966pub struct GitEntryRef<'a> {
5967    pub entry: &'a Entry,
5968    pub git_summary: GitSummary,
5969}
5970
5971impl<'a> GitEntryRef<'a> {
5972    pub fn to_owned(&self) -> GitEntry {
5973        GitEntry {
5974            entry: self.entry.clone(),
5975            git_summary: self.git_summary,
5976        }
5977    }
5978}
5979
5980impl<'a> Deref for GitEntryRef<'a> {
5981    type Target = Entry;
5982
5983    fn deref(&self) -> &Self::Target {
5984        &self.entry
5985    }
5986}
5987
5988impl<'a> AsRef<Entry> for GitEntryRef<'a> {
5989    fn as_ref(&self) -> &Entry {
5990        self.entry
5991    }
5992}
5993
5994#[derive(Debug, Clone, PartialEq, Eq)]
5995pub struct GitEntry {
5996    pub entry: Entry,
5997    pub git_summary: GitSummary,
5998}
5999
6000impl GitEntry {
6001    pub fn to_ref(&self) -> GitEntryRef {
6002        GitEntryRef {
6003            entry: &self.entry,
6004            git_summary: self.git_summary,
6005        }
6006    }
6007}
6008
6009impl Deref for GitEntry {
6010    type Target = Entry;
6011
6012    fn deref(&self) -> &Self::Target {
6013        &self.entry
6014    }
6015}
6016
6017impl AsRef<Entry> for GitEntry {
6018    fn as_ref(&self) -> &Entry {
6019        &self.entry
6020    }
6021}
6022
6023/// Walks the worktree entries and their associated git statuses.
6024pub struct GitTraversal<'a> {
6025    traversal: Traversal<'a>,
6026    current_entry_summary: Option<GitSummary>,
6027    repo_location: Option<(
6028        &'a RepositoryEntry,
6029        Cursor<'a, StatusEntry, PathProgress<'a>>,
6030    )>,
6031}
6032
6033impl<'a> GitTraversal<'a> {
6034    fn synchronize_statuses(&mut self, reset: bool) {
6035        self.current_entry_summary = None;
6036
6037        let Some(entry) = self.traversal.cursor.item() else {
6038            return;
6039        };
6040
6041        let Some(repo) = self.traversal.snapshot.repository_for_path(&entry.path) else {
6042            self.repo_location = None;
6043            return;
6044        };
6045
6046        // Update our state if we changed repositories.
6047        if reset
6048            || self
6049                .repo_location
6050                .as_ref()
6051                .map(|(prev_repo, _)| &prev_repo.work_directory)
6052                != Some(&repo.work_directory)
6053        {
6054            self.repo_location = Some((repo, repo.statuses_by_path.cursor::<PathProgress>(&())));
6055        }
6056
6057        let Some((repo, statuses)) = &mut self.repo_location else {
6058            return;
6059        };
6060
6061        let repo_path = repo.relativize(&entry.path).unwrap();
6062
6063        if entry.is_dir() {
6064            let mut statuses = statuses.clone();
6065            statuses.seek_forward(&PathTarget::Path(repo_path.as_ref()), Bias::Left, &());
6066            let summary =
6067                statuses.summary(&PathTarget::Successor(repo_path.as_ref()), Bias::Left, &());
6068
6069            self.current_entry_summary = Some(summary);
6070        } else if entry.is_file() {
6071            // For a file entry, park the cursor on the corresponding status
6072            if statuses.seek_forward(&PathTarget::Path(repo_path.as_ref()), Bias::Left, &()) {
6073                // TODO: Investigate statuses.item() being None here.
6074                self.current_entry_summary = statuses.item().map(|item| item.status.into());
6075            } else {
6076                self.current_entry_summary = Some(GitSummary::UNCHANGED);
6077            }
6078        }
6079    }
6080
6081    pub fn advance(&mut self) -> bool {
6082        self.advance_by(1)
6083    }
6084
6085    pub fn advance_by(&mut self, count: usize) -> bool {
6086        let found = self.traversal.advance_by(count);
6087        self.synchronize_statuses(false);
6088        found
6089    }
6090
6091    pub fn advance_to_sibling(&mut self) -> bool {
6092        let found = self.traversal.advance_to_sibling();
6093        self.synchronize_statuses(false);
6094        found
6095    }
6096
6097    pub fn back_to_parent(&mut self) -> bool {
6098        let found = self.traversal.back_to_parent();
6099        self.synchronize_statuses(true);
6100        found
6101    }
6102
6103    pub fn start_offset(&self) -> usize {
6104        self.traversal.start_offset()
6105    }
6106
6107    pub fn end_offset(&self) -> usize {
6108        self.traversal.end_offset()
6109    }
6110
6111    pub fn entry(&self) -> Option<GitEntryRef<'a>> {
6112        let entry = self.traversal.cursor.item()?;
6113        let git_summary = self.current_entry_summary.unwrap_or(GitSummary::UNCHANGED);
6114        Some(GitEntryRef { entry, git_summary })
6115    }
6116}
6117
6118impl<'a> Iterator for GitTraversal<'a> {
6119    type Item = GitEntryRef<'a>;
6120    fn next(&mut self) -> Option<Self::Item> {
6121        if let Some(item) = self.entry() {
6122            self.advance();
6123            Some(item)
6124        } else {
6125            None
6126        }
6127    }
6128}
6129
6130#[derive(Debug)]
6131pub struct Traversal<'a> {
6132    snapshot: &'a Snapshot,
6133    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
6134    include_ignored: bool,
6135    include_files: bool,
6136    include_dirs: bool,
6137}
6138
6139impl<'a> Traversal<'a> {
6140    fn new(
6141        snapshot: &'a Snapshot,
6142        include_files: bool,
6143        include_dirs: bool,
6144        include_ignored: bool,
6145        start_path: &Path,
6146    ) -> Self {
6147        let mut cursor = snapshot.entries_by_path.cursor(&());
6148        cursor.seek(&TraversalTarget::path(start_path), Bias::Left, &());
6149        let mut traversal = Self {
6150            snapshot,
6151            cursor,
6152            include_files,
6153            include_dirs,
6154            include_ignored,
6155        };
6156        if traversal.end_offset() == traversal.start_offset() {
6157            traversal.next();
6158        }
6159        traversal
6160    }
6161
6162    pub fn with_git_statuses(self) -> GitTraversal<'a> {
6163        let mut this = GitTraversal {
6164            traversal: self,
6165            current_entry_summary: None,
6166            repo_location: None,
6167        };
6168        this.synchronize_statuses(true);
6169        this
6170    }
6171
6172    pub fn advance(&mut self) -> bool {
6173        self.advance_by(1)
6174    }
6175
6176    pub fn advance_by(&mut self, count: usize) -> bool {
6177        self.cursor.seek_forward(
6178            &TraversalTarget::Count {
6179                count: self.end_offset() + count,
6180                include_dirs: self.include_dirs,
6181                include_files: self.include_files,
6182                include_ignored: self.include_ignored,
6183            },
6184            Bias::Left,
6185            &(),
6186        )
6187    }
6188
6189    pub fn advance_to_sibling(&mut self) -> bool {
6190        while let Some(entry) = self.cursor.item() {
6191            self.cursor
6192                .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left, &());
6193            if let Some(entry) = self.cursor.item() {
6194                if (self.include_files || !entry.is_file())
6195                    && (self.include_dirs || !entry.is_dir())
6196                    && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
6197                {
6198                    return true;
6199                }
6200            }
6201        }
6202        false
6203    }
6204
6205    pub fn back_to_parent(&mut self) -> bool {
6206        let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
6207            return false;
6208        };
6209        self.cursor
6210            .seek(&TraversalTarget::path(parent_path), Bias::Left, &())
6211    }
6212
6213    pub fn entry(&self) -> Option<&'a Entry> {
6214        self.cursor.item()
6215    }
6216
6217    pub fn start_offset(&self) -> usize {
6218        self.cursor
6219            .start()
6220            .count(self.include_files, self.include_dirs, self.include_ignored)
6221    }
6222
6223    pub fn end_offset(&self) -> usize {
6224        self.cursor
6225            .end(&())
6226            .count(self.include_files, self.include_dirs, self.include_ignored)
6227    }
6228}
6229
6230impl<'a> Iterator for Traversal<'a> {
6231    type Item = &'a Entry;
6232
6233    fn next(&mut self) -> Option<Self::Item> {
6234        if let Some(item) = self.entry() {
6235            self.advance();
6236            Some(item)
6237        } else {
6238            None
6239        }
6240    }
6241}
6242
6243#[derive(Debug, Clone, Copy)]
6244enum PathTarget<'a> {
6245    Path(&'a Path),
6246    Successor(&'a Path),
6247}
6248
6249impl<'a> PathTarget<'a> {
6250    fn cmp_path(&self, other: &Path) -> Ordering {
6251        match self {
6252            PathTarget::Path(path) => path.cmp(&other),
6253            PathTarget::Successor(path) => {
6254                if other.starts_with(path) {
6255                    Ordering::Greater
6256                } else {
6257                    Ordering::Equal
6258                }
6259            }
6260        }
6261    }
6262}
6263
6264impl<'a, 'b, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'b> {
6265    fn cmp(&self, cursor_location: &PathProgress<'a>, _: &S::Context) -> Ordering {
6266        self.cmp_path(&cursor_location.max_path)
6267    }
6268}
6269
6270impl<'a, 'b, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'b> {
6271    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &S::Context) -> Ordering {
6272        self.cmp_path(&cursor_location.max_path)
6273    }
6274}
6275
6276impl<'a, 'b> SeekTarget<'a, PathSummary<GitSummary>, (TraversalProgress<'a>, GitSummary)>
6277    for PathTarget<'b>
6278{
6279    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitSummary), _: &()) -> Ordering {
6280        self.cmp_path(&cursor_location.0.max_path)
6281    }
6282}
6283
6284#[derive(Debug)]
6285enum TraversalTarget<'a> {
6286    Path(PathTarget<'a>),
6287    Count {
6288        count: usize,
6289        include_files: bool,
6290        include_ignored: bool,
6291        include_dirs: bool,
6292    },
6293}
6294
6295impl<'a> TraversalTarget<'a> {
6296    fn path(path: &'a Path) -> Self {
6297        Self::Path(PathTarget::Path(path))
6298    }
6299
6300    fn successor(path: &'a Path) -> Self {
6301        Self::Path(PathTarget::Successor(path))
6302    }
6303
6304    fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
6305        match self {
6306            TraversalTarget::Path(path) => path.cmp_path(&progress.max_path),
6307            TraversalTarget::Count {
6308                count,
6309                include_files,
6310                include_dirs,
6311                include_ignored,
6312            } => Ord::cmp(
6313                count,
6314                &progress.count(*include_files, *include_dirs, *include_ignored),
6315            ),
6316        }
6317    }
6318}
6319
6320impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
6321    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
6322        self.cmp_progress(cursor_location)
6323    }
6324}
6325
6326impl<'a, 'b> SeekTarget<'a, PathSummary<Unit>, TraversalProgress<'a>> for TraversalTarget<'b> {
6327    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
6328        self.cmp_progress(cursor_location)
6329    }
6330}
6331
6332pub struct ChildEntriesOptions {
6333    pub include_files: bool,
6334    pub include_dirs: bool,
6335    pub include_ignored: bool,
6336}
6337
6338pub struct ChildEntriesIter<'a> {
6339    parent_path: &'a Path,
6340    traversal: Traversal<'a>,
6341}
6342
6343impl<'a> ChildEntriesIter<'a> {
6344    pub fn with_git_statuses(self) -> ChildEntriesGitIter<'a> {
6345        ChildEntriesGitIter {
6346            parent_path: self.parent_path,
6347            traversal: self.traversal.with_git_statuses(),
6348        }
6349    }
6350}
6351
6352pub struct ChildEntriesGitIter<'a> {
6353    parent_path: &'a Path,
6354    traversal: GitTraversal<'a>,
6355}
6356
6357impl<'a> Iterator for ChildEntriesIter<'a> {
6358    type Item = &'a Entry;
6359
6360    fn next(&mut self) -> Option<Self::Item> {
6361        if let Some(item) = self.traversal.entry() {
6362            if item.path.starts_with(self.parent_path) {
6363                self.traversal.advance_to_sibling();
6364                return Some(item);
6365            }
6366        }
6367        None
6368    }
6369}
6370
6371impl<'a> Iterator for ChildEntriesGitIter<'a> {
6372    type Item = GitEntryRef<'a>;
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> From<&'a Entry> for proto::Entry {
6386    fn from(entry: &'a Entry) -> Self {
6387        Self {
6388            id: entry.id.to_proto(),
6389            is_dir: entry.is_dir(),
6390            path: entry.path.as_ref().to_proto(),
6391            inode: entry.inode,
6392            mtime: entry.mtime.map(|time| time.into()),
6393            is_ignored: entry.is_ignored,
6394            is_external: entry.is_external,
6395            is_fifo: entry.is_fifo,
6396            size: Some(entry.size),
6397            canonical_path: entry
6398                .canonical_path
6399                .as_ref()
6400                .map(|path| path.as_ref().to_proto()),
6401        }
6402    }
6403}
6404
6405impl<'a> TryFrom<(&'a CharBag, &PathMatcher, proto::Entry)> for Entry {
6406    type Error = anyhow::Error;
6407
6408    fn try_from(
6409        (root_char_bag, always_included, entry): (&'a CharBag, &PathMatcher, proto::Entry),
6410    ) -> Result<Self> {
6411        let kind = if entry.is_dir {
6412            EntryKind::Dir
6413        } else {
6414            EntryKind::File
6415        };
6416
6417        let path = Arc::<Path>::from_proto(entry.path);
6418        let char_bag = char_bag_for_path(*root_char_bag, &path);
6419        let is_always_included = always_included.is_match(path.as_ref());
6420        Ok(Entry {
6421            id: ProjectEntryId::from_proto(entry.id),
6422            kind,
6423            path,
6424            inode: entry.inode,
6425            mtime: entry.mtime.map(|time| time.into()),
6426            size: entry.size.unwrap_or(0),
6427            canonical_path: entry
6428                .canonical_path
6429                .map(|path_string| Box::from(PathBuf::from_proto(path_string))),
6430            is_ignored: entry.is_ignored,
6431            is_always_included,
6432            is_external: entry.is_external,
6433            is_private: false,
6434            char_bag,
6435            is_fifo: entry.is_fifo,
6436        })
6437    }
6438}
6439
6440fn status_from_proto(
6441    simple_status: i32,
6442    status: Option<proto::GitFileStatus>,
6443) -> anyhow::Result<FileStatus> {
6444    use proto::git_file_status::Variant;
6445
6446    let Some(variant) = status.and_then(|status| status.variant) else {
6447        let code = proto::GitStatus::from_i32(simple_status)
6448            .ok_or_else(|| anyhow!("Invalid git status code: {simple_status}"))?;
6449        let result = match code {
6450            proto::GitStatus::Added => TrackedStatus {
6451                worktree_status: StatusCode::Added,
6452                index_status: StatusCode::Unmodified,
6453            }
6454            .into(),
6455            proto::GitStatus::Modified => TrackedStatus {
6456                worktree_status: StatusCode::Modified,
6457                index_status: StatusCode::Unmodified,
6458            }
6459            .into(),
6460            proto::GitStatus::Conflict => UnmergedStatus {
6461                first_head: UnmergedStatusCode::Updated,
6462                second_head: UnmergedStatusCode::Updated,
6463            }
6464            .into(),
6465            proto::GitStatus::Deleted => TrackedStatus {
6466                worktree_status: StatusCode::Deleted,
6467                index_status: StatusCode::Unmodified,
6468            }
6469            .into(),
6470            _ => return Err(anyhow!("Invalid code for simple status: {simple_status}")),
6471        };
6472        return Ok(result);
6473    };
6474
6475    let result = match variant {
6476        Variant::Untracked(_) => FileStatus::Untracked,
6477        Variant::Ignored(_) => FileStatus::Ignored,
6478        Variant::Unmerged(unmerged) => {
6479            let [first_head, second_head] =
6480                [unmerged.first_head, unmerged.second_head].map(|head| {
6481                    let code = proto::GitStatus::from_i32(head)
6482                        .ok_or_else(|| anyhow!("Invalid git status code: {head}"))?;
6483                    let result = match code {
6484                        proto::GitStatus::Added => UnmergedStatusCode::Added,
6485                        proto::GitStatus::Updated => UnmergedStatusCode::Updated,
6486                        proto::GitStatus::Deleted => UnmergedStatusCode::Deleted,
6487                        _ => return Err(anyhow!("Invalid code for unmerged status: {code:?}")),
6488                    };
6489                    Ok(result)
6490                });
6491            let [first_head, second_head] = [first_head?, second_head?];
6492            UnmergedStatus {
6493                first_head,
6494                second_head,
6495            }
6496            .into()
6497        }
6498        Variant::Tracked(tracked) => {
6499            let [index_status, worktree_status] = [tracked.index_status, tracked.worktree_status]
6500                .map(|status| {
6501                    let code = proto::GitStatus::from_i32(status)
6502                        .ok_or_else(|| anyhow!("Invalid git status code: {status}"))?;
6503                    let result = match code {
6504                        proto::GitStatus::Modified => StatusCode::Modified,
6505                        proto::GitStatus::TypeChanged => StatusCode::TypeChanged,
6506                        proto::GitStatus::Added => StatusCode::Added,
6507                        proto::GitStatus::Deleted => StatusCode::Deleted,
6508                        proto::GitStatus::Renamed => StatusCode::Renamed,
6509                        proto::GitStatus::Copied => StatusCode::Copied,
6510                        proto::GitStatus::Unmodified => StatusCode::Unmodified,
6511                        _ => return Err(anyhow!("Invalid code for tracked status: {code:?}")),
6512                    };
6513                    Ok(result)
6514                });
6515            let [index_status, worktree_status] = [index_status?, worktree_status?];
6516            TrackedStatus {
6517                index_status,
6518                worktree_status,
6519            }
6520            .into()
6521        }
6522    };
6523    Ok(result)
6524}
6525
6526fn status_to_proto(status: FileStatus) -> proto::GitFileStatus {
6527    use proto::git_file_status::{Tracked, Unmerged, Variant};
6528
6529    let variant = match status {
6530        FileStatus::Untracked => Variant::Untracked(Default::default()),
6531        FileStatus::Ignored => Variant::Ignored(Default::default()),
6532        FileStatus::Unmerged(UnmergedStatus {
6533            first_head,
6534            second_head,
6535        }) => Variant::Unmerged(Unmerged {
6536            first_head: unmerged_status_to_proto(first_head),
6537            second_head: unmerged_status_to_proto(second_head),
6538        }),
6539        FileStatus::Tracked(TrackedStatus {
6540            index_status,
6541            worktree_status,
6542        }) => Variant::Tracked(Tracked {
6543            index_status: tracked_status_to_proto(index_status),
6544            worktree_status: tracked_status_to_proto(worktree_status),
6545        }),
6546    };
6547    proto::GitFileStatus {
6548        variant: Some(variant),
6549    }
6550}
6551
6552fn unmerged_status_to_proto(code: UnmergedStatusCode) -> i32 {
6553    match code {
6554        UnmergedStatusCode::Added => proto::GitStatus::Added as _,
6555        UnmergedStatusCode::Deleted => proto::GitStatus::Deleted as _,
6556        UnmergedStatusCode::Updated => proto::GitStatus::Updated as _,
6557    }
6558}
6559
6560fn tracked_status_to_proto(code: StatusCode) -> i32 {
6561    match code {
6562        StatusCode::Added => proto::GitStatus::Added as _,
6563        StatusCode::Deleted => proto::GitStatus::Deleted as _,
6564        StatusCode::Modified => proto::GitStatus::Modified as _,
6565        StatusCode::Renamed => proto::GitStatus::Renamed as _,
6566        StatusCode::TypeChanged => proto::GitStatus::TypeChanged as _,
6567        StatusCode::Copied => proto::GitStatus::Copied as _,
6568        StatusCode::Unmodified => proto::GitStatus::Unmodified as _,
6569    }
6570}
6571
6572#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
6573pub struct ProjectEntryId(usize);
6574
6575impl ProjectEntryId {
6576    pub const MAX: Self = Self(usize::MAX);
6577    pub const MIN: Self = Self(usize::MIN);
6578
6579    pub fn new(counter: &AtomicUsize) -> Self {
6580        Self(counter.fetch_add(1, SeqCst))
6581    }
6582
6583    pub fn from_proto(id: u64) -> Self {
6584        Self(id as usize)
6585    }
6586
6587    pub fn to_proto(&self) -> u64 {
6588        self.0 as u64
6589    }
6590
6591    pub fn to_usize(&self) -> usize {
6592        self.0
6593    }
6594}
6595
6596#[cfg(any(test, feature = "test-support"))]
6597impl CreatedEntry {
6598    pub fn to_included(self) -> Option<Entry> {
6599        match self {
6600            CreatedEntry::Included(entry) => Some(entry),
6601            CreatedEntry::Excluded { .. } => None,
6602        }
6603    }
6604}