worktree.rs

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