worktree.rs

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