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