worktree.rs

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