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