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