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