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