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