worktree.rs

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