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