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