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