worktree.rs

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