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    /// Get the repository whose work directory corresponds to the given path.
2587    pub(crate) fn repository(&self, work_directory: PathKey) -> Option<RepositoryEntry> {
2588        self.repositories.get(&work_directory, &()).cloned()
2589    }
2590
2591    /// Get the repository whose work directory contains the given path.
2592    pub fn repository_for_path(&self, path: &Path) -> Option<&RepositoryEntry> {
2593        let mut cursor = self.repositories.cursor::<PathProgress>(&());
2594        let mut repository = None;
2595
2596        // Git repositories may contain other git repositories. As a side effect of
2597        // lexicographic sorting by path, deeper repositories will be after higher repositories
2598        // So, let's loop through every matching repository until we can't find any more to find
2599        // the deepest repository that could contain this path.
2600        while cursor.seek_forward(&PathTarget::Contains(path), Bias::Left, &())
2601            && cursor.item().is_some()
2602        {
2603            repository = cursor.item();
2604            cursor.next(&());
2605        }
2606
2607        repository
2608    }
2609
2610    /// Given an ordered iterator of entries, returns an iterator of those entries,
2611    /// along with their containing git repository.
2612    pub fn entries_with_repositories<'a>(
2613        &'a self,
2614        entries: impl 'a + Iterator<Item = &'a Entry>,
2615    ) -> impl 'a + Iterator<Item = (&'a Entry, Option<&'a RepositoryEntry>)> {
2616        let mut containing_repos = Vec::<&RepositoryEntry>::new();
2617        let mut repositories = self.repositories().iter().peekable();
2618        entries.map(move |entry| {
2619            while let Some(repository) = containing_repos.last() {
2620                if repository.directory_contains(&entry.path) {
2621                    break;
2622                } else {
2623                    containing_repos.pop();
2624                }
2625            }
2626            while let Some(repository) = repositories.peek() {
2627                if repository.directory_contains(&entry.path) {
2628                    containing_repos.push(repositories.next().unwrap());
2629                } else {
2630                    break;
2631                }
2632            }
2633            let repo = containing_repos.last().copied();
2634            (entry, repo)
2635        })
2636    }
2637
2638    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
2639        let empty_path = Path::new("");
2640        self.entries_by_path
2641            .cursor::<()>(&())
2642            .filter(move |entry| entry.path.as_ref() != empty_path)
2643            .map(|entry| &entry.path)
2644    }
2645
2646    pub fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
2647        let mut cursor = self.entries_by_path.cursor(&());
2648        cursor.seek(&TraversalTarget::path(parent_path), Bias::Right, &());
2649        let traversal = Traversal {
2650            snapshot: self,
2651            cursor,
2652            include_files: true,
2653            include_dirs: true,
2654            include_ignored: true,
2655        };
2656        ChildEntriesIter {
2657            traversal,
2658            parent_path,
2659        }
2660    }
2661
2662    pub fn root_entry(&self) -> Option<&Entry> {
2663        self.entry_for_path("")
2664    }
2665
2666    pub fn root_dir(&self) -> Option<Arc<Path>> {
2667        self.root_entry()
2668            .filter(|entry| entry.is_dir())
2669            .map(|_| self.abs_path().clone())
2670    }
2671
2672    pub fn root_name(&self) -> &str {
2673        &self.root_name
2674    }
2675
2676    pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
2677        self.repositories
2678            .get(&PathKey(Path::new("").into()), &())
2679            .map(|entry| entry.to_owned())
2680    }
2681
2682    pub fn git_entry(&self, work_directory_path: Arc<Path>) -> Option<RepositoryEntry> {
2683        self.repositories
2684            .get(&PathKey(work_directory_path), &())
2685            .map(|entry| entry.to_owned())
2686    }
2687
2688    pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
2689        self.repositories.iter()
2690    }
2691
2692    pub fn scan_id(&self) -> usize {
2693        self.scan_id
2694    }
2695
2696    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
2697        let path = path.as_ref();
2698        self.traverse_from_path(true, true, true, path)
2699            .entry()
2700            .and_then(|entry| {
2701                if entry.path.as_ref() == path {
2702                    Some(entry)
2703                } else {
2704                    None
2705                }
2706            })
2707    }
2708
2709    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2710        let entry = self.entries_by_id.get(&id, &())?;
2711        self.entry_for_path(&entry.path)
2712    }
2713
2714    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
2715        self.entry_for_path(path.as_ref()).map(|e| e.inode)
2716    }
2717}
2718
2719impl LocalSnapshot {
2720    pub fn local_repo_for_path(&self, path: &Path) -> Option<&LocalRepositoryEntry> {
2721        let repository_entry = self.repository_for_path(path)?;
2722        let work_directory_id = repository_entry.work_directory_id();
2723        self.git_repositories.get(&work_directory_id)
2724    }
2725
2726    fn build_update(
2727        &self,
2728        project_id: u64,
2729        worktree_id: u64,
2730        entry_changes: UpdatedEntriesSet,
2731        repo_changes: UpdatedGitRepositoriesSet,
2732    ) -> proto::UpdateWorktree {
2733        let mut updated_entries = Vec::new();
2734        let mut removed_entries = Vec::new();
2735        let mut updated_repositories = Vec::new();
2736        let mut removed_repositories = Vec::new();
2737
2738        for (_, entry_id, path_change) in entry_changes.iter() {
2739            if let PathChange::Removed = path_change {
2740                removed_entries.push(entry_id.0 as u64);
2741            } else if let Some(entry) = self.entry_for_id(*entry_id) {
2742                updated_entries.push(proto::Entry::from(entry));
2743            }
2744        }
2745
2746        for (work_dir_path, change) in repo_changes.iter() {
2747            let new_repo = self.repositories.get(&PathKey(work_dir_path.clone()), &());
2748            match (&change.old_repository, new_repo) {
2749                (Some(old_repo), Some(new_repo)) => {
2750                    updated_repositories.push(new_repo.build_update(old_repo));
2751                }
2752                (None, Some(new_repo)) => {
2753                    updated_repositories.push(new_repo.initial_update());
2754                }
2755                (Some(old_repo), None) => {
2756                    removed_repositories.push(old_repo.work_directory_id.to_proto());
2757                }
2758                _ => {}
2759            }
2760        }
2761
2762        removed_entries.sort_unstable();
2763        updated_entries.sort_unstable_by_key(|e| e.id);
2764        removed_repositories.sort_unstable();
2765        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2766
2767        // TODO - optimize, knowing that removed_entries are sorted.
2768        removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2769
2770        proto::UpdateWorktree {
2771            project_id,
2772            worktree_id,
2773            abs_path: self.abs_path().to_string_lossy().into(),
2774            root_name: self.root_name().to_string(),
2775            updated_entries,
2776            removed_entries,
2777            scan_id: self.scan_id as u64,
2778            is_last_update: self.completed_scan_id == self.scan_id,
2779            updated_repositories,
2780            removed_repositories,
2781        }
2782    }
2783
2784    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2785        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2786            let abs_path = self.abs_path.as_path().join(&entry.path);
2787            match smol::block_on(build_gitignore(&abs_path, fs)) {
2788                Ok(ignore) => {
2789                    self.ignores_by_parent_abs_path
2790                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2791                }
2792                Err(error) => {
2793                    log::error!(
2794                        "error loading .gitignore file {:?} - {:?}",
2795                        &entry.path,
2796                        error
2797                    );
2798                }
2799            }
2800        }
2801
2802        if entry.kind == EntryKind::PendingDir {
2803            if let Some(existing_entry) =
2804                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2805            {
2806                entry.kind = existing_entry.kind;
2807            }
2808        }
2809
2810        let scan_id = self.scan_id;
2811        let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2812        if let Some(removed) = removed {
2813            if removed.id != entry.id {
2814                self.entries_by_id.remove(&removed.id, &());
2815            }
2816        }
2817        self.entries_by_id.insert_or_replace(
2818            PathEntry {
2819                id: entry.id,
2820                path: entry.path.clone(),
2821                is_ignored: entry.is_ignored,
2822                scan_id,
2823            },
2824            &(),
2825        );
2826
2827        entry
2828    }
2829
2830    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2831        let mut inodes = TreeSet::default();
2832        for ancestor in path.ancestors().skip(1) {
2833            if let Some(entry) = self.entry_for_path(ancestor) {
2834                inodes.insert(entry.inode);
2835            }
2836        }
2837        inodes
2838    }
2839
2840    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2841        let mut new_ignores = Vec::new();
2842        for (index, ancestor) in abs_path.ancestors().enumerate() {
2843            if index > 0 {
2844                if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2845                    new_ignores.push((ancestor, Some(ignore.clone())));
2846                } else {
2847                    new_ignores.push((ancestor, None));
2848                }
2849            }
2850            if ancestor.join(*DOT_GIT).exists() {
2851                break;
2852            }
2853        }
2854
2855        let mut ignore_stack = IgnoreStack::none();
2856        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2857            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2858                ignore_stack = IgnoreStack::all();
2859                break;
2860            } else if let Some(ignore) = ignore {
2861                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2862            }
2863        }
2864
2865        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2866            ignore_stack = IgnoreStack::all();
2867        }
2868
2869        ignore_stack
2870    }
2871
2872    #[cfg(test)]
2873    pub(crate) fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2874        self.entries_by_path
2875            .cursor::<()>(&())
2876            .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2877    }
2878
2879    #[cfg(test)]
2880    pub fn check_invariants(&self, git_state: bool) {
2881        use pretty_assertions::assert_eq;
2882
2883        assert_eq!(
2884            self.entries_by_path
2885                .cursor::<()>(&())
2886                .map(|e| (&e.path, e.id))
2887                .collect::<Vec<_>>(),
2888            self.entries_by_id
2889                .cursor::<()>(&())
2890                .map(|e| (&e.path, e.id))
2891                .collect::<collections::BTreeSet<_>>()
2892                .into_iter()
2893                .collect::<Vec<_>>(),
2894            "entries_by_path and entries_by_id are inconsistent"
2895        );
2896
2897        let mut files = self.files(true, 0);
2898        let mut visible_files = self.files(false, 0);
2899        for entry in self.entries_by_path.cursor::<()>(&()) {
2900            if entry.is_file() {
2901                assert_eq!(files.next().unwrap().inode, entry.inode);
2902                if (!entry.is_ignored && !entry.is_external) || entry.is_always_included {
2903                    assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2904                }
2905            }
2906        }
2907
2908        assert!(files.next().is_none());
2909        assert!(visible_files.next().is_none());
2910
2911        let mut bfs_paths = Vec::new();
2912        let mut stack = self
2913            .root_entry()
2914            .map(|e| e.path.as_ref())
2915            .into_iter()
2916            .collect::<Vec<_>>();
2917        while let Some(path) = stack.pop() {
2918            bfs_paths.push(path);
2919            let ix = stack.len();
2920            for child_entry in self.child_entries(path) {
2921                stack.insert(ix, &child_entry.path);
2922            }
2923        }
2924
2925        let dfs_paths_via_iter = self
2926            .entries_by_path
2927            .cursor::<()>(&())
2928            .map(|e| e.path.as_ref())
2929            .collect::<Vec<_>>();
2930        assert_eq!(bfs_paths, dfs_paths_via_iter);
2931
2932        let dfs_paths_via_traversal = self
2933            .entries(true, 0)
2934            .map(|e| e.path.as_ref())
2935            .collect::<Vec<_>>();
2936        assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2937
2938        if git_state {
2939            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2940                let ignore_parent_path = ignore_parent_abs_path
2941                    .strip_prefix(self.abs_path.as_path())
2942                    .unwrap();
2943                assert!(self.entry_for_path(ignore_parent_path).is_some());
2944                assert!(self
2945                    .entry_for_path(ignore_parent_path.join(*GITIGNORE))
2946                    .is_some());
2947            }
2948        }
2949    }
2950
2951    #[cfg(test)]
2952    fn check_git_invariants(&self) {
2953        let dotgit_paths = self
2954            .git_repositories
2955            .iter()
2956            .map(|repo| repo.1.dot_git_dir_abs_path.clone())
2957            .collect::<HashSet<_>>();
2958        let work_dir_paths = self
2959            .repositories
2960            .iter()
2961            .map(|repo| repo.work_directory.path.clone())
2962            .collect::<HashSet<_>>();
2963        assert_eq!(dotgit_paths.len(), work_dir_paths.len());
2964        assert_eq!(self.repositories.iter().count(), work_dir_paths.len());
2965        assert_eq!(self.git_repositories.iter().count(), work_dir_paths.len());
2966        for entry in self.repositories.iter() {
2967            self.git_repositories.get(&entry.work_directory_id).unwrap();
2968        }
2969    }
2970
2971    #[cfg(test)]
2972    pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2973        let mut paths = Vec::new();
2974        for entry in self.entries_by_path.cursor::<()>(&()) {
2975            if include_ignored || !entry.is_ignored {
2976                paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2977            }
2978        }
2979        paths.sort_by(|a, b| a.0.cmp(b.0));
2980        paths
2981    }
2982}
2983
2984impl BackgroundScannerState {
2985    fn should_scan_directory(&self, entry: &Entry) -> bool {
2986        (!entry.is_external && (!entry.is_ignored || entry.is_always_included))
2987            || entry.path.file_name() == Some(*DOT_GIT)
2988            || entry.path.file_name() == Some(local_settings_folder_relative_path().as_os_str())
2989            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2990            || self
2991                .paths_to_scan
2992                .iter()
2993                .any(|p| p.starts_with(&entry.path))
2994            || self
2995                .path_prefixes_to_scan
2996                .iter()
2997                .any(|p| entry.path.starts_with(p))
2998    }
2999
3000    fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
3001        let path = entry.path.clone();
3002        let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
3003        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
3004
3005        if !ancestor_inodes.contains(&entry.inode) {
3006            ancestor_inodes.insert(entry.inode);
3007            scan_job_tx
3008                .try_send(ScanJob {
3009                    abs_path,
3010                    path,
3011                    ignore_stack,
3012                    scan_queue: scan_job_tx.clone(),
3013                    ancestor_inodes,
3014                    is_external: entry.is_external,
3015                })
3016                .unwrap();
3017        }
3018    }
3019
3020    fn reuse_entry_id(&mut self, entry: &mut Entry) {
3021        if let Some(mtime) = entry.mtime {
3022            // If an entry with the same inode was removed from the worktree during this scan,
3023            // then it *might* represent the same file or directory. But the OS might also have
3024            // re-used the inode for a completely different file or directory.
3025            //
3026            // Conditionally reuse the old entry's id:
3027            // * if the mtime is the same, the file was probably been renamed.
3028            // * if the path is the same, the file may just have been updated
3029            if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
3030                if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
3031                    entry.id = removed_entry.id;
3032                }
3033            } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
3034                entry.id = existing_entry.id;
3035            }
3036        }
3037    }
3038
3039    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
3040        self.reuse_entry_id(&mut entry);
3041        let entry = self.snapshot.insert_entry(entry, fs);
3042        if entry.path.file_name() == Some(&DOT_GIT) {
3043            self.insert_git_repository(entry.path.clone(), fs, watcher);
3044        }
3045
3046        #[cfg(test)]
3047        self.snapshot.check_invariants(false);
3048
3049        entry
3050    }
3051
3052    fn populate_dir(
3053        &mut self,
3054        parent_path: &Arc<Path>,
3055        entries: impl IntoIterator<Item = Entry>,
3056        ignore: Option<Arc<Gitignore>>,
3057    ) {
3058        let mut parent_entry = if let Some(parent_entry) = self
3059            .snapshot
3060            .entries_by_path
3061            .get(&PathKey(parent_path.clone()), &())
3062        {
3063            parent_entry.clone()
3064        } else {
3065            log::warn!(
3066                "populating a directory {:?} that has been removed",
3067                parent_path
3068            );
3069            return;
3070        };
3071
3072        match parent_entry.kind {
3073            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
3074            EntryKind::Dir => {}
3075            _ => return,
3076        }
3077
3078        if let Some(ignore) = ignore {
3079            let abs_parent_path = self.snapshot.abs_path.as_path().join(parent_path).into();
3080            self.snapshot
3081                .ignores_by_parent_abs_path
3082                .insert(abs_parent_path, (ignore, false));
3083        }
3084
3085        let parent_entry_id = parent_entry.id;
3086        self.scanned_dirs.insert(parent_entry_id);
3087        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
3088        let mut entries_by_id_edits = Vec::new();
3089
3090        for entry in entries {
3091            entries_by_id_edits.push(Edit::Insert(PathEntry {
3092                id: entry.id,
3093                path: entry.path.clone(),
3094                is_ignored: entry.is_ignored,
3095                scan_id: self.snapshot.scan_id,
3096            }));
3097            entries_by_path_edits.push(Edit::Insert(entry));
3098        }
3099
3100        self.snapshot
3101            .entries_by_path
3102            .edit(entries_by_path_edits, &());
3103        self.snapshot.entries_by_id.edit(entries_by_id_edits, &());
3104
3105        if let Err(ix) = self.changed_paths.binary_search(parent_path) {
3106            self.changed_paths.insert(ix, parent_path.clone());
3107        }
3108
3109        #[cfg(test)]
3110        self.snapshot.check_invariants(false);
3111    }
3112
3113    fn remove_path(&mut self, path: &Path) {
3114        let mut new_entries;
3115        let removed_entries;
3116        {
3117            let mut cursor = self
3118                .snapshot
3119                .entries_by_path
3120                .cursor::<TraversalProgress>(&());
3121            new_entries = cursor.slice(&TraversalTarget::path(path), Bias::Left, &());
3122            removed_entries = cursor.slice(&TraversalTarget::successor(path), Bias::Left, &());
3123            new_entries.append(cursor.suffix(&()), &());
3124        }
3125        self.snapshot.entries_by_path = new_entries;
3126
3127        let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
3128        for entry in removed_entries.cursor::<()>(&()) {
3129            match self.removed_entries.entry(entry.inode) {
3130                hash_map::Entry::Occupied(mut e) => {
3131                    let prev_removed_entry = e.get_mut();
3132                    if entry.id > prev_removed_entry.id {
3133                        *prev_removed_entry = entry.clone();
3134                    }
3135                }
3136                hash_map::Entry::Vacant(e) => {
3137                    e.insert(entry.clone());
3138                }
3139            }
3140
3141            if entry.path.file_name() == Some(&GITIGNORE) {
3142                let abs_parent_path = self
3143                    .snapshot
3144                    .abs_path
3145                    .as_path()
3146                    .join(entry.path.parent().unwrap());
3147                if let Some((_, needs_update)) = self
3148                    .snapshot
3149                    .ignores_by_parent_abs_path
3150                    .get_mut(abs_parent_path.as_path())
3151                {
3152                    *needs_update = true;
3153                }
3154            }
3155
3156            if let Err(ix) = removed_ids.binary_search(&entry.id) {
3157                removed_ids.insert(ix, entry.id);
3158            }
3159        }
3160
3161        self.snapshot.entries_by_id.edit(
3162            removed_ids.iter().map(|&id| Edit::Remove(id)).collect(),
3163            &(),
3164        );
3165        self.snapshot
3166            .git_repositories
3167            .retain(|id, _| removed_ids.binary_search(id).is_err());
3168        self.snapshot.repositories.retain(&(), |repository| {
3169            !repository.work_directory.starts_with(path)
3170        });
3171
3172        #[cfg(test)]
3173        self.snapshot.check_invariants(false);
3174    }
3175
3176    fn insert_git_repository(
3177        &mut self,
3178        dot_git_path: Arc<Path>,
3179        fs: &dyn Fs,
3180        watcher: &dyn Watcher,
3181    ) -> Option<LocalRepositoryEntry> {
3182        let work_dir_path: Arc<Path> = match dot_git_path.parent() {
3183            Some(parent_dir) => {
3184                // Guard against repositories inside the repository metadata
3185                if parent_dir.iter().any(|component| component == *DOT_GIT) {
3186                    log::info!(
3187                        "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
3188                    );
3189                    return None;
3190                };
3191                log::info!(
3192                    "building git repository, `.git` path in the worktree: {dot_git_path:?}"
3193                );
3194
3195                parent_dir.into()
3196            }
3197            None => {
3198                // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
3199                // no files inside that directory are tracked by git, so no need to build the repo around it
3200                log::info!(
3201                    "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
3202                );
3203                return None;
3204            }
3205        };
3206
3207        self.insert_git_repository_for_path(work_dir_path, dot_git_path, None, fs, watcher)
3208    }
3209
3210    fn insert_git_repository_for_path(
3211        &mut self,
3212        work_dir_path: Arc<Path>,
3213        dot_git_path: Arc<Path>,
3214        location_in_repo: Option<Arc<Path>>,
3215        fs: &dyn Fs,
3216        watcher: &dyn Watcher,
3217    ) -> Option<LocalRepositoryEntry> {
3218        let work_dir_id = self
3219            .snapshot
3220            .entry_for_path(work_dir_path.clone())
3221            .map(|entry| entry.id)?;
3222
3223        if self.snapshot.git_repositories.get(&work_dir_id).is_some() {
3224            return None;
3225        }
3226
3227        let dot_git_abs_path = self.snapshot.abs_path.as_path().join(&dot_git_path);
3228
3229        let t0 = Instant::now();
3230        let repository = fs.open_repo(&dot_git_abs_path)?;
3231
3232        let actual_repo_path = repository.dot_git_dir();
3233
3234        let actual_dot_git_dir_abs_path = smol::block_on(find_git_dir(&actual_repo_path, fs))?;
3235        watcher.add(&actual_repo_path).log_err()?;
3236
3237        let dot_git_worktree_abs_path = if actual_dot_git_dir_abs_path.as_ref() == dot_git_abs_path
3238        {
3239            None
3240        } else {
3241            // The two paths could be different because we opened a git worktree.
3242            // When that happens, the .git path in the worktree (`dot_git_abs_path`) is a file that
3243            // points to the worktree-subdirectory in the actual .git directory (`git_dir_path`)
3244            watcher.add(&dot_git_abs_path).log_err()?;
3245            Some(Arc::from(dot_git_abs_path))
3246        };
3247
3248        log::trace!("constructed libgit2 repo in {:?}", t0.elapsed());
3249        let work_directory = WorkDirectory {
3250            path: work_dir_path.clone(),
3251            location_in_repo,
3252        };
3253
3254        if let Some(git_hosting_provider_registry) = self.git_hosting_provider_registry.clone() {
3255            git_hosting_providers::register_additional_providers(
3256                git_hosting_provider_registry,
3257                repository.clone(),
3258            );
3259        }
3260
3261        self.snapshot.repositories.insert_or_replace(
3262            RepositoryEntry {
3263                work_directory_id: work_dir_id,
3264                work_directory: work_directory.clone(),
3265                branch: repository.branch_name().map(Into::into),
3266                statuses_by_path: Default::default(),
3267            },
3268            &(),
3269        );
3270
3271        let local_repository = LocalRepositoryEntry {
3272            work_directory: work_directory.clone(),
3273            git_dir_scan_id: 0,
3274            status_scan_id: 0,
3275            repo_ptr: repository.clone(),
3276            dot_git_dir_abs_path: actual_dot_git_dir_abs_path,
3277            dot_git_worktree_abs_path,
3278        };
3279
3280        self.snapshot
3281            .git_repositories
3282            .insert(work_dir_id, local_repository.clone());
3283
3284        Some(local_repository)
3285    }
3286}
3287
3288async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
3289    if path.file_name() == Some(&*DOT_GIT) {
3290        return true;
3291    }
3292
3293    // If we're in a bare repository, we are not inside a `.git` folder. In a
3294    // bare repository, the root folder contains what would normally be in the
3295    // `.git` folder.
3296    let head_metadata = fs.metadata(&path.join("HEAD")).await;
3297    if !matches!(head_metadata, Ok(Some(_))) {
3298        return false;
3299    }
3300    let config_metadata = fs.metadata(&path.join("config")).await;
3301    matches!(config_metadata, Ok(Some(_)))
3302}
3303
3304async fn find_git_dir(path: &Path, fs: &dyn Fs) -> Option<Arc<Path>> {
3305    for ancestor in path.ancestors() {
3306        if is_git_dir(ancestor, fs).await {
3307            return Some(Arc::from(ancestor));
3308        }
3309    }
3310    None
3311}
3312
3313async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
3314    let contents = fs.load(abs_path).await?;
3315    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
3316    let mut builder = GitignoreBuilder::new(parent);
3317    for line in contents.lines() {
3318        builder.add_line(Some(abs_path.into()), line)?;
3319    }
3320    Ok(builder.build()?)
3321}
3322
3323impl Deref for Worktree {
3324    type Target = Snapshot;
3325
3326    fn deref(&self) -> &Self::Target {
3327        match self {
3328            Worktree::Local(worktree) => &worktree.snapshot,
3329            Worktree::Remote(worktree) => &worktree.snapshot,
3330        }
3331    }
3332}
3333
3334impl Deref for LocalWorktree {
3335    type Target = LocalSnapshot;
3336
3337    fn deref(&self) -> &Self::Target {
3338        &self.snapshot
3339    }
3340}
3341
3342impl Deref for RemoteWorktree {
3343    type Target = Snapshot;
3344
3345    fn deref(&self) -> &Self::Target {
3346        &self.snapshot
3347    }
3348}
3349
3350impl fmt::Debug for LocalWorktree {
3351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3352        self.snapshot.fmt(f)
3353    }
3354}
3355
3356impl fmt::Debug for Snapshot {
3357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3358        struct EntriesById<'a>(&'a SumTree<PathEntry>);
3359        struct EntriesByPath<'a>(&'a SumTree<Entry>);
3360
3361        impl<'a> fmt::Debug for EntriesByPath<'a> {
3362            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3363                f.debug_map()
3364                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3365                    .finish()
3366            }
3367        }
3368
3369        impl<'a> fmt::Debug for EntriesById<'a> {
3370            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3371                f.debug_list().entries(self.0.iter()).finish()
3372            }
3373        }
3374
3375        f.debug_struct("Snapshot")
3376            .field("id", &self.id)
3377            .field("root_name", &self.root_name)
3378            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3379            .field("entries_by_id", &EntriesById(&self.entries_by_id))
3380            .finish()
3381    }
3382}
3383
3384#[derive(Clone, PartialEq)]
3385pub struct File {
3386    pub worktree: Model<Worktree>,
3387    pub path: Arc<Path>,
3388    pub disk_state: DiskState,
3389    pub entry_id: Option<ProjectEntryId>,
3390    pub is_local: bool,
3391    pub is_private: bool,
3392}
3393
3394impl language::File for File {
3395    fn as_local(&self) -> Option<&dyn language::LocalFile> {
3396        if self.is_local {
3397            Some(self)
3398        } else {
3399            None
3400        }
3401    }
3402
3403    fn disk_state(&self) -> DiskState {
3404        self.disk_state
3405    }
3406
3407    fn path(&self) -> &Arc<Path> {
3408        &self.path
3409    }
3410
3411    fn full_path(&self, cx: &AppContext) -> PathBuf {
3412        let mut full_path = PathBuf::new();
3413        let worktree = self.worktree.read(cx);
3414
3415        if worktree.is_visible() {
3416            full_path.push(worktree.root_name());
3417        } else {
3418            let path = worktree.abs_path();
3419
3420            if worktree.is_local() && path.starts_with(home_dir().as_path()) {
3421                full_path.push("~");
3422                full_path.push(path.strip_prefix(home_dir().as_path()).unwrap());
3423            } else {
3424                full_path.push(path)
3425            }
3426        }
3427
3428        if self.path.components().next().is_some() {
3429            full_path.push(&self.path);
3430        }
3431
3432        full_path
3433    }
3434
3435    /// Returns the last component of this handle's absolute path. If this handle refers to the root
3436    /// of its worktree, then this method will return the name of the worktree itself.
3437    fn file_name<'a>(&'a self, cx: &'a AppContext) -> &'a OsStr {
3438        self.path
3439            .file_name()
3440            .unwrap_or_else(|| OsStr::new(&self.worktree.read(cx).root_name))
3441    }
3442
3443    fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
3444        self.worktree.read(cx).id()
3445    }
3446
3447    fn as_any(&self) -> &dyn Any {
3448        self
3449    }
3450
3451    fn to_proto(&self, cx: &AppContext) -> rpc::proto::File {
3452        rpc::proto::File {
3453            worktree_id: self.worktree.read(cx).id().to_proto(),
3454            entry_id: self.entry_id.map(|id| id.to_proto()),
3455            path: self.path.to_string_lossy().into(),
3456            mtime: self.disk_state.mtime().map(|time| time.into()),
3457            is_deleted: self.disk_state == DiskState::Deleted,
3458        }
3459    }
3460
3461    fn is_private(&self) -> bool {
3462        self.is_private
3463    }
3464}
3465
3466impl language::LocalFile for File {
3467    fn abs_path(&self, cx: &AppContext) -> PathBuf {
3468        let worktree_path = &self.worktree.read(cx).as_local().unwrap().abs_path;
3469        if self.path.as_ref() == Path::new("") {
3470            worktree_path.as_path().to_path_buf()
3471        } else {
3472            worktree_path.as_path().join(&self.path)
3473        }
3474    }
3475
3476    fn load(&self, cx: &AppContext) -> Task<Result<String>> {
3477        let worktree = self.worktree.read(cx).as_local().unwrap();
3478        let abs_path = worktree.absolutize(&self.path);
3479        let fs = worktree.fs.clone();
3480        cx.background_executor()
3481            .spawn(async move { fs.load(&abs_path?).await })
3482    }
3483
3484    fn load_bytes(&self, cx: &AppContext) -> Task<Result<Vec<u8>>> {
3485        let worktree = self.worktree.read(cx).as_local().unwrap();
3486        let abs_path = worktree.absolutize(&self.path);
3487        let fs = worktree.fs.clone();
3488        cx.background_executor()
3489            .spawn(async move { fs.load_bytes(&abs_path?).await })
3490    }
3491}
3492
3493impl File {
3494    pub fn for_entry(entry: Entry, worktree: Model<Worktree>) -> Arc<Self> {
3495        Arc::new(Self {
3496            worktree,
3497            path: entry.path.clone(),
3498            disk_state: if let Some(mtime) = entry.mtime {
3499                DiskState::Present { mtime }
3500            } else {
3501                DiskState::New
3502            },
3503            entry_id: Some(entry.id),
3504            is_local: true,
3505            is_private: entry.is_private,
3506        })
3507    }
3508
3509    pub fn from_proto(
3510        proto: rpc::proto::File,
3511        worktree: Model<Worktree>,
3512        cx: &AppContext,
3513    ) -> Result<Self> {
3514        let worktree_id = worktree
3515            .read(cx)
3516            .as_remote()
3517            .ok_or_else(|| anyhow!("not remote"))?
3518            .id();
3519
3520        if worktree_id.to_proto() != proto.worktree_id {
3521            return Err(anyhow!("worktree id does not match file"));
3522        }
3523
3524        let disk_state = if proto.is_deleted {
3525            DiskState::Deleted
3526        } else {
3527            if let Some(mtime) = proto.mtime.map(&Into::into) {
3528                DiskState::Present { mtime }
3529            } else {
3530                DiskState::New
3531            }
3532        };
3533
3534        Ok(Self {
3535            worktree,
3536            path: Path::new(&proto.path).into(),
3537            disk_state,
3538            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3539            is_local: false,
3540            is_private: false,
3541        })
3542    }
3543
3544    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3545        file.and_then(|f| f.as_any().downcast_ref())
3546    }
3547
3548    pub fn worktree_id(&self, cx: &AppContext) -> WorktreeId {
3549        self.worktree.read(cx).id()
3550    }
3551
3552    pub fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
3553        match self.disk_state {
3554            DiskState::Deleted => None,
3555            _ => self.entry_id,
3556        }
3557    }
3558}
3559
3560#[derive(Clone, Debug, PartialEq, Eq)]
3561pub struct Entry {
3562    pub id: ProjectEntryId,
3563    pub kind: EntryKind,
3564    pub path: Arc<Path>,
3565    pub inode: u64,
3566    pub mtime: Option<MTime>,
3567
3568    pub canonical_path: Option<Box<Path>>,
3569    /// Whether this entry is ignored by Git.
3570    ///
3571    /// We only scan ignored entries once the directory is expanded and
3572    /// exclude them from searches.
3573    pub is_ignored: bool,
3574
3575    /// Whether this entry is always included in searches.
3576    ///
3577    /// This is used for entries that are always included in searches, even
3578    /// if they are ignored by git. Overridden by file_scan_exclusions.
3579    pub is_always_included: bool,
3580
3581    /// Whether this entry's canonical path is outside of the worktree.
3582    /// This means the entry is only accessible from the worktree root via a
3583    /// symlink.
3584    ///
3585    /// We only scan entries outside of the worktree once the symlinked
3586    /// directory is expanded. External entries are treated like gitignored
3587    /// entries in that they are not included in searches.
3588    pub is_external: bool,
3589
3590    /// Whether this entry is considered to be a `.env` file.
3591    pub is_private: bool,
3592    /// The entry's size on disk, in bytes.
3593    pub size: u64,
3594    pub char_bag: CharBag,
3595    pub is_fifo: bool,
3596}
3597
3598#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3599pub enum EntryKind {
3600    UnloadedDir,
3601    PendingDir,
3602    Dir,
3603    File,
3604}
3605
3606#[derive(Clone, Copy, Debug, PartialEq)]
3607pub enum PathChange {
3608    /// A filesystem entry was was created.
3609    Added,
3610    /// A filesystem entry was removed.
3611    Removed,
3612    /// A filesystem entry was updated.
3613    Updated,
3614    /// A filesystem entry was either updated or added. We don't know
3615    /// whether or not it already existed, because the path had not
3616    /// been loaded before the event.
3617    AddedOrUpdated,
3618    /// A filesystem entry was found during the initial scan of the worktree.
3619    Loaded,
3620}
3621
3622#[derive(Debug)]
3623pub struct GitRepositoryChange {
3624    /// The previous state of the repository, if it already existed.
3625    pub old_repository: Option<RepositoryEntry>,
3626}
3627
3628pub type UpdatedEntriesSet = Arc<[(Arc<Path>, ProjectEntryId, PathChange)]>;
3629pub type UpdatedGitRepositoriesSet = Arc<[(Arc<Path>, GitRepositoryChange)]>;
3630
3631#[derive(Clone, Debug, PartialEq, Eq)]
3632pub struct StatusEntry {
3633    pub repo_path: RepoPath,
3634    pub status: FileStatus,
3635}
3636
3637impl StatusEntry {
3638    pub fn is_staged(&self) -> Option<bool> {
3639        self.status.is_staged()
3640    }
3641
3642    fn to_proto(&self) -> proto::StatusEntry {
3643        let simple_status = match self.status {
3644            FileStatus::Ignored | FileStatus::Untracked => proto::GitStatus::Added as i32,
3645            FileStatus::Unmerged { .. } => proto::GitStatus::Conflict as i32,
3646            FileStatus::Tracked(TrackedStatus {
3647                index_status,
3648                worktree_status,
3649            }) => tracked_status_to_proto(if worktree_status != StatusCode::Unmodified {
3650                worktree_status
3651            } else {
3652                index_status
3653            }),
3654        };
3655        proto::StatusEntry {
3656            repo_path: self.repo_path.to_proto(),
3657            simple_status,
3658            status: Some(status_to_proto(self.status)),
3659        }
3660    }
3661}
3662
3663impl TryFrom<proto::StatusEntry> for StatusEntry {
3664    type Error = anyhow::Error;
3665
3666    fn try_from(value: proto::StatusEntry) -> Result<Self, Self::Error> {
3667        let repo_path = RepoPath(Path::new(&value.repo_path).into());
3668        let status = status_from_proto(value.simple_status, value.status)?;
3669        Ok(Self { repo_path, status })
3670    }
3671}
3672
3673#[derive(Clone, Debug)]
3674struct PathProgress<'a> {
3675    max_path: &'a Path,
3676}
3677
3678#[derive(Clone, Debug)]
3679pub struct PathSummary<S> {
3680    max_path: Arc<Path>,
3681    item_summary: S,
3682}
3683
3684impl<S: Summary> Summary for PathSummary<S> {
3685    type Context = S::Context;
3686
3687    fn zero(cx: &Self::Context) -> Self {
3688        Self {
3689            max_path: Path::new("").into(),
3690            item_summary: S::zero(cx),
3691        }
3692    }
3693
3694    fn add_summary(&mut self, rhs: &Self, cx: &Self::Context) {
3695        self.max_path = rhs.max_path.clone();
3696        self.item_summary.add_summary(&rhs.item_summary, cx);
3697    }
3698}
3699
3700impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathProgress<'a> {
3701    fn zero(_: &<PathSummary<S> as Summary>::Context) -> Self {
3702        Self {
3703            max_path: Path::new(""),
3704        }
3705    }
3706
3707    fn add_summary(
3708        &mut self,
3709        summary: &'a PathSummary<S>,
3710        _: &<PathSummary<S> as Summary>::Context,
3711    ) {
3712        self.max_path = summary.max_path.as_ref()
3713    }
3714}
3715
3716impl sum_tree::Item for RepositoryEntry {
3717    type Summary = PathSummary<Unit>;
3718
3719    fn summary(&self, _: &<Self::Summary as Summary>::Context) -> Self::Summary {
3720        PathSummary {
3721            max_path: self.work_directory.path.clone(),
3722            item_summary: Unit,
3723        }
3724    }
3725}
3726
3727impl sum_tree::KeyedItem for RepositoryEntry {
3728    type Key = PathKey;
3729
3730    fn key(&self) -> Self::Key {
3731        PathKey(self.work_directory.path.clone())
3732    }
3733}
3734
3735impl sum_tree::Item for StatusEntry {
3736    type Summary = PathSummary<GitSummary>;
3737
3738    fn summary(&self, _: &<Self::Summary as Summary>::Context) -> Self::Summary {
3739        PathSummary {
3740            max_path: self.repo_path.0.clone(),
3741            item_summary: self.status.summary(),
3742        }
3743    }
3744}
3745
3746impl sum_tree::KeyedItem for StatusEntry {
3747    type Key = PathKey;
3748
3749    fn key(&self) -> Self::Key {
3750        PathKey(self.repo_path.0.clone())
3751    }
3752}
3753
3754impl<'a> sum_tree::Dimension<'a, PathSummary<GitSummary>> for GitSummary {
3755    fn zero(_cx: &()) -> Self {
3756        Default::default()
3757    }
3758
3759    fn add_summary(&mut self, summary: &'a PathSummary<GitSummary>, _: &()) {
3760        *self += summary.item_summary
3761    }
3762}
3763
3764impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathKey {
3765    fn zero(_: &S::Context) -> Self {
3766        Default::default()
3767    }
3768
3769    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: &S::Context) {
3770        self.0 = summary.max_path.clone();
3771    }
3772}
3773
3774impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for TraversalProgress<'a> {
3775    fn zero(_cx: &S::Context) -> Self {
3776        Default::default()
3777    }
3778
3779    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: &S::Context) {
3780        self.max_path = summary.max_path.as_ref();
3781    }
3782}
3783
3784impl Entry {
3785    fn new(
3786        path: Arc<Path>,
3787        metadata: &fs::Metadata,
3788        next_entry_id: &AtomicUsize,
3789        root_char_bag: CharBag,
3790        canonical_path: Option<Box<Path>>,
3791    ) -> Self {
3792        let char_bag = char_bag_for_path(root_char_bag, &path);
3793        Self {
3794            id: ProjectEntryId::new(next_entry_id),
3795            kind: if metadata.is_dir {
3796                EntryKind::PendingDir
3797            } else {
3798                EntryKind::File
3799            },
3800            path,
3801            inode: metadata.inode,
3802            mtime: Some(metadata.mtime),
3803            size: metadata.len,
3804            canonical_path,
3805            is_ignored: false,
3806            is_always_included: false,
3807            is_external: false,
3808            is_private: false,
3809            char_bag,
3810            is_fifo: metadata.is_fifo,
3811        }
3812    }
3813
3814    pub fn is_created(&self) -> bool {
3815        self.mtime.is_some()
3816    }
3817
3818    pub fn is_dir(&self) -> bool {
3819        self.kind.is_dir()
3820    }
3821
3822    pub fn is_file(&self) -> bool {
3823        self.kind.is_file()
3824    }
3825}
3826
3827impl EntryKind {
3828    pub fn is_dir(&self) -> bool {
3829        matches!(
3830            self,
3831            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3832        )
3833    }
3834
3835    pub fn is_unloaded(&self) -> bool {
3836        matches!(self, EntryKind::UnloadedDir)
3837    }
3838
3839    pub fn is_file(&self) -> bool {
3840        matches!(self, EntryKind::File)
3841    }
3842}
3843
3844impl sum_tree::Item for Entry {
3845    type Summary = EntrySummary;
3846
3847    fn summary(&self, _cx: &()) -> Self::Summary {
3848        let non_ignored_count = if (self.is_ignored || self.is_external) && !self.is_always_included
3849        {
3850            0
3851        } else {
3852            1
3853        };
3854        let file_count;
3855        let non_ignored_file_count;
3856        if self.is_file() {
3857            file_count = 1;
3858            non_ignored_file_count = non_ignored_count;
3859        } else {
3860            file_count = 0;
3861            non_ignored_file_count = 0;
3862        }
3863
3864        EntrySummary {
3865            max_path: self.path.clone(),
3866            count: 1,
3867            non_ignored_count,
3868            file_count,
3869            non_ignored_file_count,
3870        }
3871    }
3872}
3873
3874impl sum_tree::KeyedItem for Entry {
3875    type Key = PathKey;
3876
3877    fn key(&self) -> Self::Key {
3878        PathKey(self.path.clone())
3879    }
3880}
3881
3882#[derive(Clone, Debug)]
3883pub struct EntrySummary {
3884    max_path: Arc<Path>,
3885    count: usize,
3886    non_ignored_count: usize,
3887    file_count: usize,
3888    non_ignored_file_count: usize,
3889}
3890
3891impl Default for EntrySummary {
3892    fn default() -> Self {
3893        Self {
3894            max_path: Arc::from(Path::new("")),
3895            count: 0,
3896            non_ignored_count: 0,
3897            file_count: 0,
3898            non_ignored_file_count: 0,
3899        }
3900    }
3901}
3902
3903impl sum_tree::Summary for EntrySummary {
3904    type Context = ();
3905
3906    fn zero(_cx: &()) -> Self {
3907        Default::default()
3908    }
3909
3910    fn add_summary(&mut self, rhs: &Self, _: &()) {
3911        self.max_path = rhs.max_path.clone();
3912        self.count += rhs.count;
3913        self.non_ignored_count += rhs.non_ignored_count;
3914        self.file_count += rhs.file_count;
3915        self.non_ignored_file_count += rhs.non_ignored_file_count;
3916    }
3917}
3918
3919#[derive(Clone, Debug)]
3920struct PathEntry {
3921    id: ProjectEntryId,
3922    path: Arc<Path>,
3923    is_ignored: bool,
3924    scan_id: usize,
3925}
3926
3927impl sum_tree::Item for PathEntry {
3928    type Summary = PathEntrySummary;
3929
3930    fn summary(&self, _cx: &()) -> Self::Summary {
3931        PathEntrySummary { max_id: self.id }
3932    }
3933}
3934
3935impl sum_tree::KeyedItem for PathEntry {
3936    type Key = ProjectEntryId;
3937
3938    fn key(&self) -> Self::Key {
3939        self.id
3940    }
3941}
3942
3943#[derive(Clone, Debug, Default)]
3944struct PathEntrySummary {
3945    max_id: ProjectEntryId,
3946}
3947
3948impl sum_tree::Summary for PathEntrySummary {
3949    type Context = ();
3950
3951    fn zero(_cx: &Self::Context) -> Self {
3952        Default::default()
3953    }
3954
3955    fn add_summary(&mut self, summary: &Self, _: &Self::Context) {
3956        self.max_id = summary.max_id;
3957    }
3958}
3959
3960impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3961    fn zero(_cx: &()) -> Self {
3962        Default::default()
3963    }
3964
3965    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: &()) {
3966        *self = summary.max_id;
3967    }
3968}
3969
3970#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
3971pub struct PathKey(Arc<Path>);
3972
3973impl Default for PathKey {
3974    fn default() -> Self {
3975        Self(Path::new("").into())
3976    }
3977}
3978
3979impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3980    fn zero(_cx: &()) -> Self {
3981        Default::default()
3982    }
3983
3984    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
3985        self.0 = summary.max_path.clone();
3986    }
3987}
3988
3989struct BackgroundScanner {
3990    state: Mutex<BackgroundScannerState>,
3991    fs: Arc<dyn Fs>,
3992    fs_case_sensitive: bool,
3993    status_updates_tx: UnboundedSender<ScanState>,
3994    executor: BackgroundExecutor,
3995    scan_requests_rx: channel::Receiver<ScanRequest>,
3996    path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
3997    next_entry_id: Arc<AtomicUsize>,
3998    phase: BackgroundScannerPhase,
3999    watcher: Arc<dyn Watcher>,
4000    settings: WorktreeSettings,
4001    share_private_files: bool,
4002}
4003
4004#[derive(PartialEq)]
4005enum BackgroundScannerPhase {
4006    InitialScan,
4007    EventsReceivedDuringInitialScan,
4008    Events,
4009}
4010
4011impl BackgroundScanner {
4012    async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
4013        use futures::FutureExt as _;
4014
4015        // If the worktree root does not contain a git repository, then find
4016        // the git repository in an ancestor directory. Find any gitignore files
4017        // in ancestor directories.
4018        let root_abs_path = self.state.lock().snapshot.abs_path.clone();
4019        for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
4020            if index != 0 {
4021                if let Ok(ignore) =
4022                    build_gitignore(&ancestor.join(*GITIGNORE), self.fs.as_ref()).await
4023                {
4024                    self.state
4025                        .lock()
4026                        .snapshot
4027                        .ignores_by_parent_abs_path
4028                        .insert(ancestor.into(), (ignore.into(), false));
4029                }
4030            }
4031
4032            let ancestor_dot_git = ancestor.join(*DOT_GIT);
4033            // Check whether the directory or file called `.git` exists (in the
4034            // case of worktrees it's a file.)
4035            if self
4036                .fs
4037                .metadata(&ancestor_dot_git)
4038                .await
4039                .is_ok_and(|metadata| metadata.is_some())
4040            {
4041                if index != 0 {
4042                    // We canonicalize, since the FS events use the canonicalized path.
4043                    if let Some(ancestor_dot_git) =
4044                        self.fs.canonicalize(&ancestor_dot_git).await.log_err()
4045                    {
4046                        // We associate the external git repo with our root folder and
4047                        // also mark where in the git repo the root folder is located.
4048                        self.state.lock().insert_git_repository_for_path(
4049                            Path::new("").into(),
4050                            ancestor_dot_git.into(),
4051                            Some(
4052                                root_abs_path
4053                                    .as_path()
4054                                    .strip_prefix(ancestor)
4055                                    .unwrap()
4056                                    .into(),
4057                            ),
4058                            self.fs.as_ref(),
4059                            self.watcher.as_ref(),
4060                        );
4061                    };
4062                }
4063
4064                // Reached root of git repository.
4065                break;
4066            }
4067        }
4068
4069        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4070        {
4071            let mut state = self.state.lock();
4072            state.snapshot.scan_id += 1;
4073            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
4074                let ignore_stack = state
4075                    .snapshot
4076                    .ignore_stack_for_abs_path(root_abs_path.as_path(), true);
4077                if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
4078                    root_entry.is_ignored = true;
4079                    state.insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4080                }
4081                state.enqueue_scan_dir(root_abs_path.into(), &root_entry, &scan_job_tx);
4082            }
4083        };
4084
4085        // Perform an initial scan of the directory.
4086        drop(scan_job_tx);
4087        self.scan_dirs(true, scan_job_rx).await;
4088        {
4089            let mut state = self.state.lock();
4090            state.snapshot.completed_scan_id = state.snapshot.scan_id;
4091        }
4092
4093        self.send_status_update(false, SmallVec::new());
4094
4095        // Process any any FS events that occurred while performing the initial scan.
4096        // For these events, update events cannot be as precise, because we didn't
4097        // have the previous state loaded yet.
4098        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
4099        if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
4100            while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4101                paths.extend(more_paths);
4102            }
4103            self.process_events(paths.into_iter().map(Into::into).collect())
4104                .await;
4105        }
4106
4107        // Continue processing events until the worktree is dropped.
4108        self.phase = BackgroundScannerPhase::Events;
4109
4110        loop {
4111            select_biased! {
4112                // Process any path refresh requests from the worktree. Prioritize
4113                // these before handling changes reported by the filesystem.
4114                request = self.next_scan_request().fuse() => {
4115                    let Ok(request) = request else { break };
4116                    if !self.process_scan_request(request, false).await {
4117                        return;
4118                    }
4119                }
4120
4121                path_prefix = self.path_prefixes_to_scan_rx.recv().fuse() => {
4122                    let Ok(path_prefix) = path_prefix else { break };
4123                    log::trace!("adding path prefix {:?}", path_prefix);
4124
4125                    let did_scan = self.forcibly_load_paths(&[path_prefix.clone()]).await;
4126                    if did_scan {
4127                        let abs_path =
4128                        {
4129                            let mut state = self.state.lock();
4130                            state.path_prefixes_to_scan.insert(path_prefix.clone());
4131                            state.snapshot.abs_path.as_path().join(&path_prefix)
4132                        };
4133
4134                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
4135                            self.process_events(vec![abs_path]).await;
4136                        }
4137                    }
4138                }
4139
4140                paths = fs_events_rx.next().fuse() => {
4141                    let Some(mut paths) = paths else { break };
4142                    while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
4143                        paths.extend(more_paths);
4144                    }
4145                    self.process_events(paths.into_iter().map(Into::into).collect()).await;
4146                }
4147            }
4148        }
4149    }
4150
4151    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
4152        log::debug!("rescanning paths {:?}", request.relative_paths);
4153
4154        request.relative_paths.sort_unstable();
4155        self.forcibly_load_paths(&request.relative_paths).await;
4156
4157        let root_path = self.state.lock().snapshot.abs_path.clone();
4158        let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
4159            Ok(path) => path,
4160            Err(err) => {
4161                log::error!("failed to canonicalize root path: {}", err);
4162                return true;
4163            }
4164        };
4165        let abs_paths = request
4166            .relative_paths
4167            .iter()
4168            .map(|path| {
4169                if path.file_name().is_some() {
4170                    root_canonical_path.join(path)
4171                } else {
4172                    root_canonical_path.clone()
4173                }
4174            })
4175            .collect::<Vec<_>>();
4176
4177        {
4178            let mut state = self.state.lock();
4179            let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
4180            state.snapshot.scan_id += 1;
4181            if is_idle {
4182                state.snapshot.completed_scan_id = state.snapshot.scan_id;
4183            }
4184        }
4185
4186        self.reload_entries_for_paths(
4187            root_path.into(),
4188            root_canonical_path,
4189            &request.relative_paths,
4190            abs_paths,
4191            None,
4192        )
4193        .await;
4194
4195        self.send_status_update(scanning, request.done)
4196    }
4197
4198    async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
4199        let root_path = self.state.lock().snapshot.abs_path.clone();
4200        let root_canonical_path = match self.fs.canonicalize(root_path.as_path()).await {
4201            Ok(path) => path,
4202            Err(err) => {
4203                let new_path = self
4204                    .state
4205                    .lock()
4206                    .snapshot
4207                    .root_file_handle
4208                    .clone()
4209                    .and_then(|handle| handle.current_path(&self.fs).log_err())
4210                    .map(SanitizedPath::from)
4211                    .filter(|new_path| *new_path != root_path);
4212
4213                if let Some(new_path) = new_path.as_ref() {
4214                    log::info!(
4215                        "root renamed from {} to {}",
4216                        root_path.as_path().display(),
4217                        new_path.as_path().display()
4218                    )
4219                } else {
4220                    log::warn!("root path could not be canonicalized: {}", err);
4221                }
4222                self.status_updates_tx
4223                    .unbounded_send(ScanState::RootUpdated { new_path })
4224                    .ok();
4225                return;
4226            }
4227        };
4228
4229        let mut relative_paths = Vec::with_capacity(abs_paths.len());
4230        let mut dot_git_abs_paths = Vec::new();
4231        abs_paths.sort_unstable();
4232        abs_paths.dedup_by(|a, b| a.starts_with(b));
4233        abs_paths.retain(|abs_path| {
4234            let snapshot = &self.state.lock().snapshot;
4235            {
4236                let mut is_git_related = false;
4237
4238                // We don't want to trigger .git rescan for events within .git/fsmonitor--daemon/cookies directory.
4239                #[derive(PartialEq)]
4240                enum FsMonitorParseState {
4241                    Cookies,
4242                    FsMonitor
4243                }
4244                let mut fsmonitor_parse_state = None;
4245                if let Some(dot_git_abs_path) = abs_path
4246                    .ancestors()
4247                    .find(|ancestor| {
4248                        let file_name = ancestor.file_name();
4249                        if file_name == Some(*COOKIES) {
4250                            fsmonitor_parse_state = Some(FsMonitorParseState::Cookies);
4251                            false
4252                        } else if fsmonitor_parse_state == Some(FsMonitorParseState::Cookies) && file_name == Some(*FSMONITOR_DAEMON) {
4253                            fsmonitor_parse_state = Some(FsMonitorParseState::FsMonitor);
4254                            false
4255                        } else if fsmonitor_parse_state != Some(FsMonitorParseState::FsMonitor) && smol::block_on(is_git_dir(ancestor, self.fs.as_ref())) {
4256                            true
4257                        } else {
4258                            fsmonitor_parse_state.take();
4259                            false
4260                        }
4261
4262                    })
4263                {
4264                    let dot_git_abs_path = dot_git_abs_path.to_path_buf();
4265                    if !dot_git_abs_paths.contains(&dot_git_abs_path) {
4266                        dot_git_abs_paths.push(dot_git_abs_path);
4267                    }
4268                    is_git_related = true;
4269                }
4270
4271                let relative_path: Arc<Path> =
4272                    if let Ok(path) = abs_path.strip_prefix(&root_canonical_path) {
4273                        path.into()
4274                    } else {
4275                        if is_git_related {
4276                            log::debug!(
4277                              "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
4278                            );
4279                        } else {
4280                            log::error!(
4281                              "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
4282                            );
4283                        }
4284                        return false;
4285                    };
4286
4287                let parent_dir_is_loaded = relative_path.parent().map_or(true, |parent| {
4288                    snapshot
4289                        .entry_for_path(parent)
4290                        .map_or(false, |entry| entry.kind == EntryKind::Dir)
4291                });
4292                if !parent_dir_is_loaded {
4293                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
4294                    return false;
4295                }
4296
4297                if self.settings.is_path_excluded(&relative_path) {
4298                    if !is_git_related {
4299                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
4300                    }
4301                    return false;
4302                }
4303
4304                relative_paths.push(relative_path);
4305                true
4306            }
4307        });
4308
4309        if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
4310            return;
4311        }
4312
4313        self.state.lock().snapshot.scan_id += 1;
4314
4315        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4316        log::debug!("received fs events {:?}", relative_paths);
4317        self.reload_entries_for_paths(
4318            root_path.into(),
4319            root_canonical_path,
4320            &relative_paths,
4321            abs_paths,
4322            Some(scan_job_tx.clone()),
4323        )
4324        .await;
4325
4326        self.update_ignore_statuses(scan_job_tx).await;
4327        self.scan_dirs(false, scan_job_rx).await;
4328
4329        if !dot_git_abs_paths.is_empty() {
4330            self.update_git_repositories(dot_git_abs_paths).await;
4331        }
4332
4333        {
4334            let mut state = self.state.lock();
4335            state.snapshot.completed_scan_id = state.snapshot.scan_id;
4336            for (_, entry) in mem::take(&mut state.removed_entries) {
4337                state.scanned_dirs.remove(&entry.id);
4338            }
4339        }
4340
4341        #[cfg(test)]
4342        self.state.lock().snapshot.check_git_invariants();
4343
4344        self.send_status_update(false, SmallVec::new());
4345    }
4346
4347    async fn forcibly_load_paths(&self, paths: &[Arc<Path>]) -> bool {
4348        let (scan_job_tx, scan_job_rx) = channel::unbounded();
4349        {
4350            let mut state = self.state.lock();
4351            let root_path = state.snapshot.abs_path.clone();
4352            for path in paths {
4353                for ancestor in path.ancestors() {
4354                    if let Some(entry) = state.snapshot.entry_for_path(ancestor) {
4355                        if entry.kind == EntryKind::UnloadedDir {
4356                            let abs_path = root_path.as_path().join(ancestor);
4357                            state.enqueue_scan_dir(abs_path.into(), entry, &scan_job_tx);
4358                            state.paths_to_scan.insert(path.clone());
4359                            break;
4360                        }
4361                    }
4362                }
4363            }
4364            drop(scan_job_tx);
4365        }
4366        while let Ok(job) = scan_job_rx.recv().await {
4367            self.scan_dir(&job).await.log_err();
4368        }
4369
4370        !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
4371    }
4372
4373    async fn scan_dirs(
4374        &self,
4375        enable_progress_updates: bool,
4376        scan_jobs_rx: channel::Receiver<ScanJob>,
4377    ) {
4378        use futures::FutureExt as _;
4379
4380        if self
4381            .status_updates_tx
4382            .unbounded_send(ScanState::Started)
4383            .is_err()
4384        {
4385            return;
4386        }
4387
4388        let progress_update_count = AtomicUsize::new(0);
4389        self.executor
4390            .scoped(|scope| {
4391                for _ in 0..self.executor.num_cpus() {
4392                    scope.spawn(async {
4393                        let mut last_progress_update_count = 0;
4394                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4395                        futures::pin_mut!(progress_update_timer);
4396
4397                        loop {
4398                            select_biased! {
4399                                // Process any path refresh requests before moving on to process
4400                                // the scan queue, so that user operations are prioritized.
4401                                request = self.next_scan_request().fuse() => {
4402                                    let Ok(request) = request else { break };
4403                                    if !self.process_scan_request(request, true).await {
4404                                        return;
4405                                    }
4406                                }
4407
4408                                // Send periodic progress updates to the worktree. Use an atomic counter
4409                                // to ensure that only one of the workers sends a progress update after
4410                                // the update interval elapses.
4411                                _ = progress_update_timer => {
4412                                    match progress_update_count.compare_exchange(
4413                                        last_progress_update_count,
4414                                        last_progress_update_count + 1,
4415                                        SeqCst,
4416                                        SeqCst
4417                                    ) {
4418                                        Ok(_) => {
4419                                            last_progress_update_count += 1;
4420                                            self.send_status_update(true, SmallVec::new());
4421                                        }
4422                                        Err(count) => {
4423                                            last_progress_update_count = count;
4424                                        }
4425                                    }
4426                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4427                                }
4428
4429                                // Recursively load directories from the file system.
4430                                job = scan_jobs_rx.recv().fuse() => {
4431                                    let Ok(job) = job else { break };
4432                                    if let Err(err) = self.scan_dir(&job).await {
4433                                        if job.path.as_ref() != Path::new("") {
4434                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4435                                        }
4436                                    }
4437                                }
4438                            }
4439                        }
4440                    })
4441                }
4442            })
4443            .await;
4444    }
4445
4446    fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
4447        let mut state = self.state.lock();
4448        if state.changed_paths.is_empty() && scanning {
4449            return true;
4450        }
4451
4452        let new_snapshot = state.snapshot.clone();
4453        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4454        let changes = self.build_change_set(&old_snapshot, &new_snapshot, &state.changed_paths);
4455        state.changed_paths.clear();
4456
4457        self.status_updates_tx
4458            .unbounded_send(ScanState::Updated {
4459                snapshot: new_snapshot,
4460                changes,
4461                scanning,
4462                barrier,
4463            })
4464            .is_ok()
4465    }
4466
4467    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4468        let root_abs_path;
4469        let root_char_bag;
4470        {
4471            let snapshot = &self.state.lock().snapshot;
4472            if self.settings.is_path_excluded(&job.path) {
4473                log::error!("skipping excluded directory {:?}", job.path);
4474                return Ok(());
4475            }
4476            log::debug!("scanning directory {:?}", job.path);
4477            root_abs_path = snapshot.abs_path().clone();
4478            root_char_bag = snapshot.root_char_bag;
4479        }
4480
4481        let next_entry_id = self.next_entry_id.clone();
4482        let mut ignore_stack = job.ignore_stack.clone();
4483        let mut new_ignore = None;
4484        let mut root_canonical_path = None;
4485        let mut new_entries: Vec<Entry> = Vec::new();
4486        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4487        let mut child_paths = self
4488            .fs
4489            .read_dir(&job.abs_path)
4490            .await?
4491            .filter_map(|entry| async {
4492                match entry {
4493                    Ok(entry) => Some(entry),
4494                    Err(error) => {
4495                        log::error!("error processing entry {:?}", error);
4496                        None
4497                    }
4498                }
4499            })
4500            .collect::<Vec<_>>()
4501            .await;
4502
4503        // Ensure that .git and .gitignore are processed first.
4504        swap_to_front(&mut child_paths, *GITIGNORE);
4505        swap_to_front(&mut child_paths, *DOT_GIT);
4506
4507        for child_abs_path in child_paths {
4508            let child_abs_path: Arc<Path> = child_abs_path.into();
4509            let child_name = child_abs_path.file_name().unwrap();
4510            let child_path: Arc<Path> = job.path.join(child_name).into();
4511
4512            if child_name == *DOT_GIT {
4513                let repo = self.state.lock().insert_git_repository(
4514                    child_path.clone(),
4515                    self.fs.as_ref(),
4516                    self.watcher.as_ref(),
4517                );
4518
4519                if let Some(local_repo) = repo {
4520                    self.update_git_statuses(UpdateGitStatusesJob {
4521                        local_repository: local_repo,
4522                    });
4523                }
4524            } else if child_name == *GITIGNORE {
4525                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4526                    Ok(ignore) => {
4527                        let ignore = Arc::new(ignore);
4528                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4529                        new_ignore = Some(ignore);
4530                    }
4531                    Err(error) => {
4532                        log::error!(
4533                            "error loading .gitignore file {:?} - {:?}",
4534                            child_name,
4535                            error
4536                        );
4537                    }
4538                }
4539            }
4540
4541            if self.settings.is_path_excluded(&child_path) {
4542                log::debug!("skipping excluded child entry {child_path:?}");
4543                self.state.lock().remove_path(&child_path);
4544                continue;
4545            }
4546
4547            let child_metadata = match self.fs.metadata(&child_abs_path).await {
4548                Ok(Some(metadata)) => metadata,
4549                Ok(None) => continue,
4550                Err(err) => {
4551                    log::error!("error processing {child_abs_path:?}: {err:?}");
4552                    continue;
4553                }
4554            };
4555
4556            let mut child_entry = Entry::new(
4557                child_path.clone(),
4558                &child_metadata,
4559                &next_entry_id,
4560                root_char_bag,
4561                None,
4562            );
4563
4564            if job.is_external {
4565                child_entry.is_external = true;
4566            } else if child_metadata.is_symlink {
4567                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4568                    Ok(path) => path,
4569                    Err(err) => {
4570                        log::error!(
4571                            "error reading target of symlink {:?}: {:?}",
4572                            child_abs_path,
4573                            err
4574                        );
4575                        continue;
4576                    }
4577                };
4578
4579                // lazily canonicalize the root path in order to determine if
4580                // symlinks point outside of the worktree.
4581                let root_canonical_path = match &root_canonical_path {
4582                    Some(path) => path,
4583                    None => match self.fs.canonicalize(&root_abs_path).await {
4584                        Ok(path) => root_canonical_path.insert(path),
4585                        Err(err) => {
4586                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4587                            continue;
4588                        }
4589                    },
4590                };
4591
4592                if !canonical_path.starts_with(root_canonical_path) {
4593                    child_entry.is_external = true;
4594                }
4595
4596                child_entry.canonical_path = Some(canonical_path.into());
4597            }
4598
4599            if child_entry.is_dir() {
4600                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4601                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4602
4603                // Avoid recursing until crash in the case of a recursive symlink
4604                if job.ancestor_inodes.contains(&child_entry.inode) {
4605                    new_jobs.push(None);
4606                } else {
4607                    let mut ancestor_inodes = job.ancestor_inodes.clone();
4608                    ancestor_inodes.insert(child_entry.inode);
4609
4610                    new_jobs.push(Some(ScanJob {
4611                        abs_path: child_abs_path.clone(),
4612                        path: child_path,
4613                        is_external: child_entry.is_external,
4614                        ignore_stack: if child_entry.is_ignored {
4615                            IgnoreStack::all()
4616                        } else {
4617                            ignore_stack.clone()
4618                        },
4619                        ancestor_inodes,
4620                        scan_queue: job.scan_queue.clone(),
4621                    }));
4622                }
4623            } else {
4624                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4625                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4626            }
4627
4628            {
4629                let relative_path = job.path.join(child_name);
4630                if self.is_path_private(&relative_path) {
4631                    log::debug!("detected private file: {relative_path:?}");
4632                    child_entry.is_private = true;
4633                }
4634            }
4635
4636            new_entries.push(child_entry);
4637        }
4638
4639        let mut state = self.state.lock();
4640
4641        // Identify any subdirectories that should not be scanned.
4642        let mut job_ix = 0;
4643        for entry in &mut new_entries {
4644            state.reuse_entry_id(entry);
4645            if entry.is_dir() {
4646                if state.should_scan_directory(entry) {
4647                    job_ix += 1;
4648                } else {
4649                    log::debug!("defer scanning directory {:?}", entry.path);
4650                    entry.kind = EntryKind::UnloadedDir;
4651                    new_jobs.remove(job_ix);
4652                }
4653            }
4654            if entry.is_always_included {
4655                state
4656                    .snapshot
4657                    .always_included_entries
4658                    .push(entry.path.clone());
4659            }
4660        }
4661
4662        state.populate_dir(&job.path, new_entries, new_ignore);
4663        self.watcher.add(job.abs_path.as_ref()).log_err();
4664
4665        for new_job in new_jobs.into_iter().flatten() {
4666            job.scan_queue
4667                .try_send(new_job)
4668                .expect("channel is unbounded");
4669        }
4670
4671        Ok(())
4672    }
4673
4674    /// All list arguments should be sorted before calling this function
4675    async fn reload_entries_for_paths(
4676        &self,
4677        root_abs_path: Arc<Path>,
4678        root_canonical_path: PathBuf,
4679        relative_paths: &[Arc<Path>],
4680        abs_paths: Vec<PathBuf>,
4681        scan_queue_tx: Option<Sender<ScanJob>>,
4682    ) {
4683        // grab metadata for all requested paths
4684        let metadata = futures::future::join_all(
4685            abs_paths
4686                .iter()
4687                .map(|abs_path| async move {
4688                    let metadata = self.fs.metadata(abs_path).await?;
4689                    if let Some(metadata) = metadata {
4690                        let canonical_path = self.fs.canonicalize(abs_path).await?;
4691
4692                        // If we're on a case-insensitive filesystem (default on macOS), we want
4693                        // to only ignore metadata for non-symlink files if their absolute-path matches
4694                        // the canonical-path.
4695                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4696                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
4697                        // treated as removed.
4698                        if !self.fs_case_sensitive && !metadata.is_symlink {
4699                            let canonical_file_name = canonical_path.file_name();
4700                            let file_name = abs_path.file_name();
4701                            if canonical_file_name != file_name {
4702                                return Ok(None);
4703                            }
4704                        }
4705
4706                        anyhow::Ok(Some((metadata, canonical_path)))
4707                    } else {
4708                        Ok(None)
4709                    }
4710                })
4711                .collect::<Vec<_>>(),
4712        )
4713        .await;
4714
4715        let mut state = self.state.lock();
4716        let doing_recursive_update = scan_queue_tx.is_some();
4717
4718        // Remove any entries for paths that no longer exist or are being recursively
4719        // refreshed. Do this before adding any new entries, so that renames can be
4720        // detected regardless of the order of the paths.
4721        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4722            if matches!(metadata, Ok(None)) || doing_recursive_update {
4723                log::trace!("remove path {:?}", path);
4724                state.remove_path(path);
4725            }
4726        }
4727
4728        // Group all relative paths by their git repository.
4729        let mut paths_by_git_repo = HashMap::default();
4730        for relative_path in relative_paths.iter() {
4731            let repository_data = state
4732                .snapshot
4733                .local_repo_for_path(relative_path)
4734                .zip(state.snapshot.repository_for_path(relative_path));
4735            if let Some((local_repo, entry)) = repository_data {
4736                if let Ok(repo_path) = local_repo.relativize(relative_path) {
4737                    paths_by_git_repo
4738                        .entry(local_repo.work_directory.clone())
4739                        .or_insert_with(|| RepoPaths {
4740                            entry: entry.clone(),
4741                            repo: local_repo.repo_ptr.clone(),
4742                            repo_paths: Default::default(),
4743                        })
4744                        .add_path(repo_path);
4745                }
4746            }
4747        }
4748
4749        for (work_directory, mut paths) in paths_by_git_repo {
4750            if let Ok(status) = paths.repo.status(&paths.repo_paths) {
4751                let mut changed_path_statuses = Vec::new();
4752                let statuses = paths.entry.statuses_by_path.clone();
4753                let mut cursor = statuses.cursor::<PathProgress>(&());
4754
4755                for (repo_path, status) in &*status.entries {
4756                    paths.remove_repo_path(repo_path);
4757                    if cursor.seek_forward(&PathTarget::Path(repo_path), Bias::Left, &()) {
4758                        if &cursor.item().unwrap().status == status {
4759                            continue;
4760                        }
4761                    }
4762
4763                    changed_path_statuses.push(Edit::Insert(StatusEntry {
4764                        repo_path: repo_path.clone(),
4765                        status: *status,
4766                    }));
4767                }
4768
4769                let mut cursor = statuses.cursor::<PathProgress>(&());
4770                for path in paths.repo_paths {
4771                    if cursor.seek_forward(&PathTarget::Path(&path), Bias::Left, &()) {
4772                        changed_path_statuses.push(Edit::Remove(PathKey(path.0)));
4773                    }
4774                }
4775
4776                if !changed_path_statuses.is_empty() {
4777                    let work_directory_id = state.snapshot.repositories.update(
4778                        &work_directory.path_key(),
4779                        &(),
4780                        move |repository_entry| {
4781                            repository_entry
4782                                .statuses_by_path
4783                                .edit(changed_path_statuses, &());
4784
4785                            repository_entry.work_directory_id
4786                        },
4787                    );
4788
4789                    if let Some(work_directory_id) = work_directory_id {
4790                        let scan_id = state.snapshot.scan_id;
4791                        state.snapshot.git_repositories.update(
4792                            &work_directory_id,
4793                            |local_repository_entry| {
4794                                local_repository_entry.status_scan_id = scan_id;
4795                            },
4796                        );
4797                    }
4798                }
4799            }
4800        }
4801
4802        for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4803            let abs_path: Arc<Path> = root_abs_path.join(path).into();
4804            match metadata {
4805                Ok(Some((metadata, canonical_path))) => {
4806                    let ignore_stack = state
4807                        .snapshot
4808                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
4809                    let is_external = !canonical_path.starts_with(&root_canonical_path);
4810                    let mut fs_entry = Entry::new(
4811                        path.clone(),
4812                        &metadata,
4813                        self.next_entry_id.as_ref(),
4814                        state.snapshot.root_char_bag,
4815                        if metadata.is_symlink {
4816                            Some(canonical_path.into())
4817                        } else {
4818                            None
4819                        },
4820                    );
4821
4822                    let is_dir = fs_entry.is_dir();
4823                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4824                    fs_entry.is_external = is_external;
4825                    fs_entry.is_private = self.is_path_private(path);
4826                    fs_entry.is_always_included = self.settings.is_path_always_included(path);
4827
4828                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4829                        if state.should_scan_directory(&fs_entry)
4830                            || (fs_entry.path.as_os_str().is_empty()
4831                                && abs_path.file_name() == Some(*DOT_GIT))
4832                        {
4833                            state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
4834                        } else {
4835                            fs_entry.kind = EntryKind::UnloadedDir;
4836                        }
4837                    }
4838
4839                    state.insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4840                }
4841                Ok(None) => {
4842                    self.remove_repo_path(path, &mut state.snapshot);
4843                }
4844                Err(err) => {
4845                    log::error!("error reading file {abs_path:?} on event: {err:#}");
4846                }
4847            }
4848        }
4849
4850        util::extend_sorted(
4851            &mut state.changed_paths,
4852            relative_paths.iter().cloned(),
4853            usize::MAX,
4854            Ord::cmp,
4855        );
4856    }
4857
4858    fn remove_repo_path(&self, path: &Arc<Path>, snapshot: &mut LocalSnapshot) -> Option<()> {
4859        if !path
4860            .components()
4861            .any(|component| component.as_os_str() == *DOT_GIT)
4862        {
4863            if let Some(repository) = snapshot.repository(PathKey(path.clone())) {
4864                snapshot
4865                    .git_repositories
4866                    .remove(&repository.work_directory_id);
4867                snapshot
4868                    .snapshot
4869                    .repositories
4870                    .remove(&PathKey(repository.work_directory.path.clone()), &());
4871                return Some(());
4872            }
4873        }
4874
4875        Some(())
4876    }
4877
4878    async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
4879        use futures::FutureExt as _;
4880
4881        let mut ignores_to_update = Vec::new();
4882        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4883        let prev_snapshot;
4884        {
4885            let snapshot = &mut self.state.lock().snapshot;
4886            let abs_path = snapshot.abs_path.clone();
4887            snapshot
4888                .ignores_by_parent_abs_path
4889                .retain(|parent_abs_path, (_, needs_update)| {
4890                    if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path()) {
4891                        if *needs_update {
4892                            *needs_update = false;
4893                            if snapshot.snapshot.entry_for_path(parent_path).is_some() {
4894                                ignores_to_update.push(parent_abs_path.clone());
4895                            }
4896                        }
4897
4898                        let ignore_path = parent_path.join(*GITIGNORE);
4899                        if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
4900                            return false;
4901                        }
4902                    }
4903                    true
4904                });
4905
4906            ignores_to_update.sort_unstable();
4907            let mut ignores_to_update = ignores_to_update.into_iter().peekable();
4908            while let Some(parent_abs_path) = ignores_to_update.next() {
4909                while ignores_to_update
4910                    .peek()
4911                    .map_or(false, |p| p.starts_with(&parent_abs_path))
4912                {
4913                    ignores_to_update.next().unwrap();
4914                }
4915
4916                let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
4917                ignore_queue_tx
4918                    .send_blocking(UpdateIgnoreStatusJob {
4919                        abs_path: parent_abs_path,
4920                        ignore_stack,
4921                        ignore_queue: ignore_queue_tx.clone(),
4922                        scan_queue: scan_job_tx.clone(),
4923                    })
4924                    .unwrap();
4925            }
4926
4927            prev_snapshot = snapshot.clone();
4928        }
4929        drop(ignore_queue_tx);
4930
4931        self.executor
4932            .scoped(|scope| {
4933                for _ in 0..self.executor.num_cpus() {
4934                    scope.spawn(async {
4935                        loop {
4936                            select_biased! {
4937                                // Process any path refresh requests before moving on to process
4938                                // the queue of ignore statuses.
4939                                request = self.next_scan_request().fuse() => {
4940                                    let Ok(request) = request else { break };
4941                                    if !self.process_scan_request(request, true).await {
4942                                        return;
4943                                    }
4944                                }
4945
4946                                // Recursively process directories whose ignores have changed.
4947                                job = ignore_queue_rx.recv().fuse() => {
4948                                    let Ok(job) = job else { break };
4949                                    self.update_ignore_status(job, &prev_snapshot).await;
4950                                }
4951                            }
4952                        }
4953                    });
4954                }
4955            })
4956            .await;
4957    }
4958
4959    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4960        log::trace!("update ignore status {:?}", job.abs_path);
4961
4962        let mut ignore_stack = job.ignore_stack;
4963        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4964            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4965        }
4966
4967        let mut entries_by_id_edits = Vec::new();
4968        let mut entries_by_path_edits = Vec::new();
4969        let path = job
4970            .abs_path
4971            .strip_prefix(snapshot.abs_path.as_path())
4972            .unwrap();
4973
4974        for mut entry in snapshot.child_entries(path).cloned() {
4975            let was_ignored = entry.is_ignored;
4976            let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4977            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4978
4979            if entry.is_dir() {
4980                let child_ignore_stack = if entry.is_ignored {
4981                    IgnoreStack::all()
4982                } else {
4983                    ignore_stack.clone()
4984                };
4985
4986                // Scan any directories that were previously ignored and weren't previously scanned.
4987                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4988                    let state = self.state.lock();
4989                    if state.should_scan_directory(&entry) {
4990                        state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4991                    }
4992                }
4993
4994                job.ignore_queue
4995                    .send(UpdateIgnoreStatusJob {
4996                        abs_path: abs_path.clone(),
4997                        ignore_stack: child_ignore_stack,
4998                        ignore_queue: job.ignore_queue.clone(),
4999                        scan_queue: job.scan_queue.clone(),
5000                    })
5001                    .await
5002                    .unwrap();
5003            }
5004
5005            if entry.is_ignored != was_ignored {
5006                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
5007                path_entry.scan_id = snapshot.scan_id;
5008                path_entry.is_ignored = entry.is_ignored;
5009                entries_by_id_edits.push(Edit::Insert(path_entry));
5010                entries_by_path_edits.push(Edit::Insert(entry));
5011            }
5012        }
5013
5014        let state = &mut self.state.lock();
5015        for edit in &entries_by_path_edits {
5016            if let Edit::Insert(entry) = edit {
5017                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
5018                    state.changed_paths.insert(ix, entry.path.clone());
5019                }
5020            }
5021        }
5022
5023        state
5024            .snapshot
5025            .entries_by_path
5026            .edit(entries_by_path_edits, &());
5027        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
5028    }
5029
5030    async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) {
5031        log::debug!("reloading repositories: {dot_git_paths:?}");
5032
5033        let mut repo_updates = Vec::new();
5034        {
5035            let mut state = self.state.lock();
5036            let scan_id = state.snapshot.scan_id;
5037            for dot_git_dir in dot_git_paths {
5038                let existing_repository_entry =
5039                    state
5040                        .snapshot
5041                        .git_repositories
5042                        .iter()
5043                        .find_map(|(entry_id, repo)| {
5044                            if repo.dot_git_dir_abs_path.as_ref() == &dot_git_dir
5045                                || repo.dot_git_worktree_abs_path.as_deref() == Some(&dot_git_dir)
5046                            {
5047                                Some((*entry_id, repo.clone()))
5048                            } else {
5049                                None
5050                            }
5051                        });
5052
5053                let local_repository = match existing_repository_entry {
5054                    None => {
5055                        match state.insert_git_repository(
5056                            dot_git_dir.into(),
5057                            self.fs.as_ref(),
5058                            self.watcher.as_ref(),
5059                        ) {
5060                            Some(output) => output,
5061                            None => continue,
5062                        }
5063                    }
5064                    Some((entry_id, local_repository)) => {
5065                        if local_repository.git_dir_scan_id == scan_id {
5066                            continue;
5067                        }
5068                        let Some(work_dir) = state
5069                            .snapshot
5070                            .entry_for_id(entry_id)
5071                            .map(|entry| entry.path.clone())
5072                        else {
5073                            continue;
5074                        };
5075
5076                        let branch = local_repository.repo_ptr.branch_name();
5077                        local_repository.repo_ptr.reload_index();
5078
5079                        state.snapshot.git_repositories.update(&entry_id, |entry| {
5080                            entry.git_dir_scan_id = scan_id;
5081                            entry.status_scan_id = scan_id;
5082                        });
5083                        state.snapshot.snapshot.repositories.update(
5084                            &PathKey(work_dir.clone()),
5085                            &(),
5086                            |entry| entry.branch = branch.map(Into::into),
5087                        );
5088
5089                        local_repository
5090                    }
5091                };
5092
5093                repo_updates.push(UpdateGitStatusesJob { local_repository });
5094            }
5095
5096            // Remove any git repositories whose .git entry no longer exists.
5097            let snapshot = &mut state.snapshot;
5098            let mut ids_to_preserve = HashSet::default();
5099            for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
5100                let exists_in_snapshot = snapshot
5101                    .entry_for_id(work_directory_id)
5102                    .map_or(false, |entry| {
5103                        snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
5104                    });
5105
5106                if exists_in_snapshot
5107                    || matches!(
5108                        smol::block_on(self.fs.metadata(&entry.dot_git_dir_abs_path)),
5109                        Ok(Some(_))
5110                    )
5111                {
5112                    ids_to_preserve.insert(work_directory_id);
5113                }
5114            }
5115
5116            snapshot
5117                .git_repositories
5118                .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
5119            snapshot.repositories.retain(&(), |entry| {
5120                ids_to_preserve.contains(&entry.work_directory_id)
5121            });
5122        }
5123
5124        let (mut updates_done_tx, mut updates_done_rx) = barrier::channel();
5125        self.executor
5126            .scoped(|scope| {
5127                scope.spawn(async {
5128                    for repo_update in repo_updates {
5129                        self.update_git_statuses(repo_update);
5130                    }
5131                    updates_done_tx.blocking_send(()).ok();
5132                });
5133
5134                scope.spawn(async {
5135                    loop {
5136                        select_biased! {
5137                            // Process any path refresh requests before moving on to process
5138                            // the queue of git statuses.
5139                            request = self.next_scan_request().fuse() => {
5140                                let Ok(request) = request else { break };
5141                                if !self.process_scan_request(request, true).await {
5142                                    return;
5143                                }
5144                            }
5145                            _ = updates_done_rx.recv().fuse() =>  break,
5146                        }
5147                    }
5148                });
5149            })
5150            .await;
5151    }
5152
5153    /// Update the git statuses for a given batch of entries.
5154    fn update_git_statuses(&self, job: UpdateGitStatusesJob) {
5155        log::trace!(
5156            "updating git statuses for repo {:?}",
5157            job.local_repository.work_directory.path
5158        );
5159        let t0 = Instant::now();
5160
5161        let Some(statuses) = job
5162            .local_repository
5163            .repo()
5164            .status(&[git::WORK_DIRECTORY_REPO_PATH.clone()])
5165            .log_err()
5166        else {
5167            return;
5168        };
5169        log::trace!(
5170            "computed git statuses for repo {:?} in {:?}",
5171            job.local_repository.work_directory.path,
5172            t0.elapsed()
5173        );
5174
5175        let t0 = Instant::now();
5176        let mut changed_paths = Vec::new();
5177        let snapshot = self.state.lock().snapshot.snapshot.clone();
5178
5179        let Some(mut repository) =
5180            snapshot.repository(job.local_repository.work_directory.path_key())
5181        else {
5182            log::error!("Got an UpdateGitStatusesJob for a repository that isn't in the snapshot");
5183            debug_assert!(false);
5184            return;
5185        };
5186
5187        let mut new_entries_by_path = SumTree::new(&());
5188        for (repo_path, status) in statuses.entries.iter() {
5189            let project_path = repository.work_directory.unrelativize(repo_path);
5190
5191            new_entries_by_path.insert_or_replace(
5192                StatusEntry {
5193                    repo_path: repo_path.clone(),
5194                    status: *status,
5195                },
5196                &(),
5197            );
5198
5199            if let Some(path) = project_path {
5200                changed_paths.push(path);
5201            }
5202        }
5203
5204        repository.statuses_by_path = new_entries_by_path;
5205        let mut state = self.state.lock();
5206        state
5207            .snapshot
5208            .repositories
5209            .insert_or_replace(repository, &());
5210
5211        util::extend_sorted(
5212            &mut state.changed_paths,
5213            changed_paths,
5214            usize::MAX,
5215            Ord::cmp,
5216        );
5217
5218        log::trace!(
5219            "applied git status updates for repo {:?} in {:?}",
5220            job.local_repository.work_directory.path,
5221            t0.elapsed(),
5222        );
5223    }
5224
5225    fn build_change_set(
5226        &self,
5227        old_snapshot: &Snapshot,
5228        new_snapshot: &Snapshot,
5229        event_paths: &[Arc<Path>],
5230    ) -> UpdatedEntriesSet {
5231        use BackgroundScannerPhase::*;
5232        use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
5233
5234        // Identify which paths have changed. Use the known set of changed
5235        // parent paths to optimize the search.
5236        let mut changes = Vec::new();
5237        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(&());
5238        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(&());
5239        let mut last_newly_loaded_dir_path = None;
5240        old_paths.next(&());
5241        new_paths.next(&());
5242        for path in event_paths {
5243            let path = PathKey(path.clone());
5244            if old_paths.item().map_or(false, |e| e.path < path.0) {
5245                old_paths.seek_forward(&path, Bias::Left, &());
5246            }
5247            if new_paths.item().map_or(false, |e| e.path < path.0) {
5248                new_paths.seek_forward(&path, Bias::Left, &());
5249            }
5250            loop {
5251                match (old_paths.item(), new_paths.item()) {
5252                    (Some(old_entry), Some(new_entry)) => {
5253                        if old_entry.path > path.0
5254                            && new_entry.path > path.0
5255                            && !old_entry.path.starts_with(&path.0)
5256                            && !new_entry.path.starts_with(&path.0)
5257                        {
5258                            break;
5259                        }
5260
5261                        match Ord::cmp(&old_entry.path, &new_entry.path) {
5262                            Ordering::Less => {
5263                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
5264                                old_paths.next(&());
5265                            }
5266                            Ordering::Equal => {
5267                                if self.phase == EventsReceivedDuringInitialScan {
5268                                    if old_entry.id != new_entry.id {
5269                                        changes.push((
5270                                            old_entry.path.clone(),
5271                                            old_entry.id,
5272                                            Removed,
5273                                        ));
5274                                    }
5275                                    // If the worktree was not fully initialized when this event was generated,
5276                                    // we can't know whether this entry was added during the scan or whether
5277                                    // it was merely updated.
5278                                    changes.push((
5279                                        new_entry.path.clone(),
5280                                        new_entry.id,
5281                                        AddedOrUpdated,
5282                                    ));
5283                                } else if old_entry.id != new_entry.id {
5284                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
5285                                    changes.push((new_entry.path.clone(), new_entry.id, Added));
5286                                } else if old_entry != new_entry {
5287                                    if old_entry.kind.is_unloaded() {
5288                                        last_newly_loaded_dir_path = Some(&new_entry.path);
5289                                        changes.push((
5290                                            new_entry.path.clone(),
5291                                            new_entry.id,
5292                                            Loaded,
5293                                        ));
5294                                    } else {
5295                                        changes.push((
5296                                            new_entry.path.clone(),
5297                                            new_entry.id,
5298                                            Updated,
5299                                        ));
5300                                    }
5301                                }
5302                                old_paths.next(&());
5303                                new_paths.next(&());
5304                            }
5305                            Ordering::Greater => {
5306                                let is_newly_loaded = self.phase == InitialScan
5307                                    || last_newly_loaded_dir_path
5308                                        .as_ref()
5309                                        .map_or(false, |dir| new_entry.path.starts_with(dir));
5310                                changes.push((
5311                                    new_entry.path.clone(),
5312                                    new_entry.id,
5313                                    if is_newly_loaded { Loaded } else { Added },
5314                                ));
5315                                new_paths.next(&());
5316                            }
5317                        }
5318                    }
5319                    (Some(old_entry), None) => {
5320                        changes.push((old_entry.path.clone(), old_entry.id, Removed));
5321                        old_paths.next(&());
5322                    }
5323                    (None, Some(new_entry)) => {
5324                        let is_newly_loaded = self.phase == InitialScan
5325                            || last_newly_loaded_dir_path
5326                                .as_ref()
5327                                .map_or(false, |dir| new_entry.path.starts_with(dir));
5328                        changes.push((
5329                            new_entry.path.clone(),
5330                            new_entry.id,
5331                            if is_newly_loaded { Loaded } else { Added },
5332                        ));
5333                        new_paths.next(&());
5334                    }
5335                    (None, None) => break,
5336                }
5337            }
5338        }
5339
5340        changes.into()
5341    }
5342
5343    async fn progress_timer(&self, running: bool) {
5344        if !running {
5345            return futures::future::pending().await;
5346        }
5347
5348        #[cfg(any(test, feature = "test-support"))]
5349        if self.fs.is_fake() {
5350            return self.executor.simulate_random_delay().await;
5351        }
5352
5353        smol::Timer::after(FS_WATCH_LATENCY).await;
5354    }
5355
5356    fn is_path_private(&self, path: &Path) -> bool {
5357        !self.share_private_files && self.settings.is_path_private(path)
5358    }
5359
5360    async fn next_scan_request(&self) -> Result<ScanRequest> {
5361        let mut request = self.scan_requests_rx.recv().await?;
5362        while let Ok(next_request) = self.scan_requests_rx.try_recv() {
5363            request.relative_paths.extend(next_request.relative_paths);
5364            request.done.extend(next_request.done);
5365        }
5366        Ok(request)
5367    }
5368}
5369
5370fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &OsStr) {
5371    let position = child_paths
5372        .iter()
5373        .position(|path| path.file_name().unwrap() == file);
5374    if let Some(position) = position {
5375        let temp = child_paths.remove(position);
5376        child_paths.insert(0, temp);
5377    }
5378}
5379
5380fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
5381    let mut result = root_char_bag;
5382    result.extend(
5383        path.to_string_lossy()
5384            .chars()
5385            .map(|c| c.to_ascii_lowercase()),
5386    );
5387    result
5388}
5389
5390#[derive(Debug)]
5391struct RepoPaths {
5392    repo: Arc<dyn GitRepository>,
5393    entry: RepositoryEntry,
5394    // sorted
5395    repo_paths: Vec<RepoPath>,
5396}
5397
5398impl RepoPaths {
5399    fn add_path(&mut self, repo_path: RepoPath) {
5400        match self.repo_paths.binary_search(&repo_path) {
5401            Ok(_) => {}
5402            Err(ix) => self.repo_paths.insert(ix, repo_path),
5403        }
5404    }
5405
5406    fn remove_repo_path(&mut self, repo_path: &RepoPath) {
5407        match self.repo_paths.binary_search(&repo_path) {
5408            Ok(ix) => {
5409                self.repo_paths.remove(ix);
5410            }
5411            Err(_) => {}
5412        }
5413    }
5414}
5415
5416struct ScanJob {
5417    abs_path: Arc<Path>,
5418    path: Arc<Path>,
5419    ignore_stack: Arc<IgnoreStack>,
5420    scan_queue: Sender<ScanJob>,
5421    ancestor_inodes: TreeSet<u64>,
5422    is_external: bool,
5423}
5424
5425struct UpdateIgnoreStatusJob {
5426    abs_path: Arc<Path>,
5427    ignore_stack: Arc<IgnoreStack>,
5428    ignore_queue: Sender<UpdateIgnoreStatusJob>,
5429    scan_queue: Sender<ScanJob>,
5430}
5431
5432struct UpdateGitStatusesJob {
5433    local_repository: LocalRepositoryEntry,
5434}
5435
5436pub trait WorktreeModelHandle {
5437    #[cfg(any(test, feature = "test-support"))]
5438    fn flush_fs_events<'a>(
5439        &self,
5440        cx: &'a mut gpui::TestAppContext,
5441    ) -> futures::future::LocalBoxFuture<'a, ()>;
5442
5443    #[cfg(any(test, feature = "test-support"))]
5444    fn flush_fs_events_in_root_git_repository<'a>(
5445        &self,
5446        cx: &'a mut gpui::TestAppContext,
5447    ) -> futures::future::LocalBoxFuture<'a, ()>;
5448}
5449
5450impl WorktreeModelHandle for Model<Worktree> {
5451    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5452    // occurred before the worktree was constructed. These events can cause the worktree to perform
5453    // extra directory scans, and emit extra scan-state notifications.
5454    //
5455    // This function mutates the worktree's directory and waits for those mutations to be picked up,
5456    // to ensure that all redundant FS events have already been processed.
5457    #[cfg(any(test, feature = "test-support"))]
5458    fn flush_fs_events<'a>(
5459        &self,
5460        cx: &'a mut gpui::TestAppContext,
5461    ) -> futures::future::LocalBoxFuture<'a, ()> {
5462        let file_name = "fs-event-sentinel";
5463
5464        let tree = self.clone();
5465        let (fs, root_path) = self.update(cx, |tree, _| {
5466            let tree = tree.as_local().unwrap();
5467            (tree.fs.clone(), tree.abs_path().clone())
5468        });
5469
5470        async move {
5471            fs.create_file(&root_path.join(file_name), Default::default())
5472                .await
5473                .unwrap();
5474
5475            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
5476                .await;
5477
5478            fs.remove_file(&root_path.join(file_name), Default::default())
5479                .await
5480                .unwrap();
5481            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
5482                .await;
5483
5484            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5485                .await;
5486        }
5487        .boxed_local()
5488    }
5489
5490    // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5491    // the .git folder of the root repository.
5492    // The reason for its existence is that a repository's .git folder might live *outside* of the
5493    // worktree and thus its FS events might go through a different path.
5494    // In order to flush those, we need to create artificial events in the .git folder and wait
5495    // for the repository to be reloaded.
5496    #[cfg(any(test, feature = "test-support"))]
5497    fn flush_fs_events_in_root_git_repository<'a>(
5498        &self,
5499        cx: &'a mut gpui::TestAppContext,
5500    ) -> futures::future::LocalBoxFuture<'a, ()> {
5501        let file_name = "fs-event-sentinel";
5502
5503        let tree = self.clone();
5504        let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
5505            let tree = tree.as_local().unwrap();
5506            let root_entry = tree.root_git_entry().unwrap();
5507            let local_repo_entry = tree.get_local_repo(&root_entry).unwrap();
5508            (
5509                tree.fs.clone(),
5510                local_repo_entry.dot_git_dir_abs_path.clone(),
5511                local_repo_entry.git_dir_scan_id,
5512            )
5513        });
5514
5515        let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5516            let root_entry = tree.root_git_entry().unwrap();
5517            let local_repo_entry = tree
5518                .as_local()
5519                .unwrap()
5520                .get_local_repo(&root_entry)
5521                .unwrap();
5522
5523            if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5524                *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5525                true
5526            } else {
5527                false
5528            }
5529        };
5530
5531        async move {
5532            fs.create_file(&root_path.join(file_name), Default::default())
5533                .await
5534                .unwrap();
5535
5536            cx.condition(&tree, |tree, _| {
5537                scan_id_increased(tree, &mut git_dir_scan_id)
5538            })
5539            .await;
5540
5541            fs.remove_file(&root_path.join(file_name), Default::default())
5542                .await
5543                .unwrap();
5544
5545            cx.condition(&tree, |tree, _| {
5546                scan_id_increased(tree, &mut git_dir_scan_id)
5547            })
5548            .await;
5549
5550            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5551                .await;
5552        }
5553        .boxed_local()
5554    }
5555}
5556
5557#[derive(Clone, Debug)]
5558struct TraversalProgress<'a> {
5559    max_path: &'a Path,
5560    count: usize,
5561    non_ignored_count: usize,
5562    file_count: usize,
5563    non_ignored_file_count: usize,
5564}
5565
5566impl<'a> TraversalProgress<'a> {
5567    fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5568        match (include_files, include_dirs, include_ignored) {
5569            (true, true, true) => self.count,
5570            (true, true, false) => self.non_ignored_count,
5571            (true, false, true) => self.file_count,
5572            (true, false, false) => self.non_ignored_file_count,
5573            (false, true, true) => self.count - self.file_count,
5574            (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5575            (false, false, _) => 0,
5576        }
5577    }
5578}
5579
5580impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5581    fn zero(_cx: &()) -> Self {
5582        Default::default()
5583    }
5584
5585    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
5586        self.max_path = summary.max_path.as_ref();
5587        self.count += summary.count;
5588        self.non_ignored_count += summary.non_ignored_count;
5589        self.file_count += summary.file_count;
5590        self.non_ignored_file_count += summary.non_ignored_file_count;
5591    }
5592}
5593
5594impl<'a> Default for TraversalProgress<'a> {
5595    fn default() -> Self {
5596        Self {
5597            max_path: Path::new(""),
5598            count: 0,
5599            non_ignored_count: 0,
5600            file_count: 0,
5601            non_ignored_file_count: 0,
5602        }
5603    }
5604}
5605
5606#[derive(Debug, Clone, Copy)]
5607pub struct GitEntryRef<'a> {
5608    pub entry: &'a Entry,
5609    pub git_summary: GitSummary,
5610}
5611
5612impl<'a> GitEntryRef<'a> {
5613    pub fn to_owned(&self) -> GitEntry {
5614        GitEntry {
5615            entry: self.entry.clone(),
5616            git_summary: self.git_summary,
5617        }
5618    }
5619}
5620
5621impl<'a> Deref for GitEntryRef<'a> {
5622    type Target = Entry;
5623
5624    fn deref(&self) -> &Self::Target {
5625        &self.entry
5626    }
5627}
5628
5629impl<'a> AsRef<Entry> for GitEntryRef<'a> {
5630    fn as_ref(&self) -> &Entry {
5631        self.entry
5632    }
5633}
5634
5635#[derive(Debug, Clone, PartialEq, Eq)]
5636pub struct GitEntry {
5637    pub entry: Entry,
5638    pub git_summary: GitSummary,
5639}
5640
5641impl GitEntry {
5642    pub fn to_ref(&self) -> GitEntryRef {
5643        GitEntryRef {
5644            entry: &self.entry,
5645            git_summary: self.git_summary,
5646        }
5647    }
5648}
5649
5650impl Deref for GitEntry {
5651    type Target = Entry;
5652
5653    fn deref(&self) -> &Self::Target {
5654        &self.entry
5655    }
5656}
5657
5658impl AsRef<Entry> for GitEntry {
5659    fn as_ref(&self) -> &Entry {
5660        &self.entry
5661    }
5662}
5663
5664/// Walks the worktree entries and their associated git statuses.
5665pub struct GitTraversal<'a> {
5666    traversal: Traversal<'a>,
5667    current_entry_summary: Option<GitSummary>,
5668    repo_location: Option<(
5669        &'a RepositoryEntry,
5670        Cursor<'a, StatusEntry, PathProgress<'a>>,
5671    )>,
5672}
5673
5674impl<'a> GitTraversal<'a> {
5675    fn synchronize_statuses(&mut self, reset: bool) {
5676        self.current_entry_summary = None;
5677
5678        let Some(entry) = self.traversal.cursor.item() else {
5679            return;
5680        };
5681
5682        let Some(repo) = self.traversal.snapshot.repository_for_path(&entry.path) else {
5683            self.repo_location = None;
5684            return;
5685        };
5686
5687        // Update our state if we changed repositories.
5688        if reset || self.repo_location.as_ref().map(|(prev_repo, _)| prev_repo) != Some(&repo) {
5689            self.repo_location = Some((repo, repo.statuses_by_path.cursor::<PathProgress>(&())));
5690        }
5691
5692        let Some((repo, statuses)) = &mut self.repo_location else {
5693            return;
5694        };
5695
5696        let repo_path = repo.relativize(&entry.path).unwrap();
5697
5698        if entry.is_dir() {
5699            let mut statuses = statuses.clone();
5700            statuses.seek_forward(&PathTarget::Path(repo_path.as_ref()), Bias::Left, &());
5701            let summary =
5702                statuses.summary(&PathTarget::Successor(repo_path.as_ref()), Bias::Left, &());
5703
5704            self.current_entry_summary = Some(summary);
5705        } else if entry.is_file() {
5706            // For a file entry, park the cursor on the corresponding status
5707            if statuses.seek_forward(&PathTarget::Path(repo_path.as_ref()), Bias::Left, &()) {
5708                self.current_entry_summary = Some(statuses.item().unwrap().status.into());
5709            } else {
5710                self.current_entry_summary = Some(GitSummary::zero(&()));
5711            }
5712        }
5713    }
5714
5715    pub fn advance(&mut self) -> bool {
5716        self.advance_by(1)
5717    }
5718
5719    pub fn advance_by(&mut self, count: usize) -> bool {
5720        let found = self.traversal.advance_by(count);
5721        self.synchronize_statuses(false);
5722        found
5723    }
5724
5725    pub fn advance_to_sibling(&mut self) -> bool {
5726        let found = self.traversal.advance_to_sibling();
5727        self.synchronize_statuses(false);
5728        found
5729    }
5730
5731    pub fn back_to_parent(&mut self) -> bool {
5732        let found = self.traversal.back_to_parent();
5733        self.synchronize_statuses(true);
5734        found
5735    }
5736
5737    pub fn start_offset(&self) -> usize {
5738        self.traversal.start_offset()
5739    }
5740
5741    pub fn end_offset(&self) -> usize {
5742        self.traversal.end_offset()
5743    }
5744
5745    pub fn entry(&self) -> Option<GitEntryRef<'a>> {
5746        let entry = self.traversal.cursor.item()?;
5747        let git_summary = self.current_entry_summary.unwrap_or_default();
5748        Some(GitEntryRef { entry, git_summary })
5749    }
5750}
5751
5752impl<'a> Iterator for GitTraversal<'a> {
5753    type Item = GitEntryRef<'a>;
5754    fn next(&mut self) -> Option<Self::Item> {
5755        if let Some(item) = self.entry() {
5756            self.advance();
5757            Some(item)
5758        } else {
5759            None
5760        }
5761    }
5762}
5763
5764#[derive(Debug)]
5765pub struct Traversal<'a> {
5766    snapshot: &'a Snapshot,
5767    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
5768    include_ignored: bool,
5769    include_files: bool,
5770    include_dirs: bool,
5771}
5772
5773impl<'a> Traversal<'a> {
5774    fn new(
5775        snapshot: &'a Snapshot,
5776        include_files: bool,
5777        include_dirs: bool,
5778        include_ignored: bool,
5779        start_path: &Path,
5780    ) -> Self {
5781        let mut cursor = snapshot.entries_by_path.cursor(&());
5782        cursor.seek(&TraversalTarget::path(start_path), Bias::Left, &());
5783        let mut traversal = Self {
5784            snapshot,
5785            cursor,
5786            include_files,
5787            include_dirs,
5788            include_ignored,
5789        };
5790        if traversal.end_offset() == traversal.start_offset() {
5791            traversal.next();
5792        }
5793        traversal
5794    }
5795
5796    pub fn with_git_statuses(self) -> GitTraversal<'a> {
5797        let mut this = GitTraversal {
5798            traversal: self,
5799            current_entry_summary: None,
5800            repo_location: None,
5801        };
5802        this.synchronize_statuses(true);
5803        this
5804    }
5805
5806    pub fn advance(&mut self) -> bool {
5807        self.advance_by(1)
5808    }
5809
5810    pub fn advance_by(&mut self, count: usize) -> bool {
5811        self.cursor.seek_forward(
5812            &TraversalTarget::Count {
5813                count: self.end_offset() + count,
5814                include_dirs: self.include_dirs,
5815                include_files: self.include_files,
5816                include_ignored: self.include_ignored,
5817            },
5818            Bias::Left,
5819            &(),
5820        )
5821    }
5822
5823    pub fn advance_to_sibling(&mut self) -> bool {
5824        while let Some(entry) = self.cursor.item() {
5825            self.cursor
5826                .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left, &());
5827            if let Some(entry) = self.cursor.item() {
5828                if (self.include_files || !entry.is_file())
5829                    && (self.include_dirs || !entry.is_dir())
5830                    && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5831                {
5832                    return true;
5833                }
5834            }
5835        }
5836        false
5837    }
5838
5839    pub fn back_to_parent(&mut self) -> bool {
5840        let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5841            return false;
5842        };
5843        self.cursor
5844            .seek(&TraversalTarget::path(parent_path), Bias::Left, &())
5845    }
5846
5847    pub fn entry(&self) -> Option<&'a Entry> {
5848        self.cursor.item()
5849    }
5850
5851    pub fn start_offset(&self) -> usize {
5852        self.cursor
5853            .start()
5854            .count(self.include_files, self.include_dirs, self.include_ignored)
5855    }
5856
5857    pub fn end_offset(&self) -> usize {
5858        self.cursor
5859            .end(&())
5860            .count(self.include_files, self.include_dirs, self.include_ignored)
5861    }
5862}
5863
5864impl<'a> Iterator for Traversal<'a> {
5865    type Item = &'a Entry;
5866
5867    fn next(&mut self) -> Option<Self::Item> {
5868        if let Some(item) = self.entry() {
5869            self.advance();
5870            Some(item)
5871        } else {
5872            None
5873        }
5874    }
5875}
5876
5877#[derive(Debug, Clone, Copy)]
5878enum PathTarget<'a> {
5879    Path(&'a Path),
5880    Successor(&'a Path),
5881    Contains(&'a Path),
5882}
5883
5884impl<'a> PathTarget<'a> {
5885    fn cmp_path(&self, other: &Path) -> Ordering {
5886        match self {
5887            PathTarget::Path(path) => path.cmp(&other),
5888            PathTarget::Successor(path) => {
5889                if other.starts_with(path) {
5890                    Ordering::Greater
5891                } else {
5892                    Ordering::Equal
5893                }
5894            }
5895            PathTarget::Contains(path) => {
5896                if path.starts_with(other) {
5897                    Ordering::Equal
5898                } else {
5899                    Ordering::Greater
5900                }
5901            }
5902        }
5903    }
5904}
5905
5906impl<'a, 'b, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'b> {
5907    fn cmp(&self, cursor_location: &PathProgress<'a>, _: &S::Context) -> Ordering {
5908        self.cmp_path(&cursor_location.max_path)
5909    }
5910}
5911
5912impl<'a, 'b, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'b> {
5913    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &S::Context) -> Ordering {
5914        self.cmp_path(&cursor_location.max_path)
5915    }
5916}
5917
5918impl<'a, 'b> SeekTarget<'a, PathSummary<GitSummary>, (TraversalProgress<'a>, GitSummary)>
5919    for PathTarget<'b>
5920{
5921    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitSummary), _: &()) -> Ordering {
5922        self.cmp_path(&cursor_location.0.max_path)
5923    }
5924}
5925
5926#[derive(Debug)]
5927enum TraversalTarget<'a> {
5928    Path(PathTarget<'a>),
5929    Count {
5930        count: usize,
5931        include_files: bool,
5932        include_ignored: bool,
5933        include_dirs: bool,
5934    },
5935}
5936
5937impl<'a> TraversalTarget<'a> {
5938    fn path(path: &'a Path) -> Self {
5939        Self::Path(PathTarget::Path(path))
5940    }
5941
5942    fn successor(path: &'a Path) -> Self {
5943        Self::Path(PathTarget::Successor(path))
5944    }
5945
5946    fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5947        match self {
5948            TraversalTarget::Path(path) => path.cmp_path(&progress.max_path),
5949            TraversalTarget::Count {
5950                count,
5951                include_files,
5952                include_dirs,
5953                include_ignored,
5954            } => Ord::cmp(
5955                count,
5956                &progress.count(*include_files, *include_dirs, *include_ignored),
5957            ),
5958        }
5959    }
5960}
5961
5962impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
5963    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
5964        self.cmp_progress(cursor_location)
5965    }
5966}
5967
5968impl<'a, 'b> SeekTarget<'a, PathSummary<Unit>, TraversalProgress<'a>> for TraversalTarget<'b> {
5969    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
5970        self.cmp_progress(cursor_location)
5971    }
5972}
5973
5974pub struct ChildEntriesIter<'a> {
5975    parent_path: &'a Path,
5976    traversal: Traversal<'a>,
5977}
5978
5979impl<'a> ChildEntriesIter<'a> {
5980    pub fn with_git_statuses(self) -> ChildEntriesGitIter<'a> {
5981        ChildEntriesGitIter {
5982            parent_path: self.parent_path,
5983            traversal: self.traversal.with_git_statuses(),
5984        }
5985    }
5986}
5987
5988pub struct ChildEntriesGitIter<'a> {
5989    parent_path: &'a Path,
5990    traversal: GitTraversal<'a>,
5991}
5992
5993impl<'a> Iterator for ChildEntriesIter<'a> {
5994    type Item = &'a Entry;
5995
5996    fn next(&mut self) -> Option<Self::Item> {
5997        if let Some(item) = self.traversal.entry() {
5998            if item.path.starts_with(self.parent_path) {
5999                self.traversal.advance_to_sibling();
6000                return Some(item);
6001            }
6002        }
6003        None
6004    }
6005}
6006
6007impl<'a> Iterator for ChildEntriesGitIter<'a> {
6008    type Item = GitEntryRef<'a>;
6009
6010    fn next(&mut self) -> Option<Self::Item> {
6011        if let Some(item) = self.traversal.entry() {
6012            if item.path.starts_with(self.parent_path) {
6013                self.traversal.advance_to_sibling();
6014                return Some(item);
6015            }
6016        }
6017        None
6018    }
6019}
6020
6021impl<'a> From<&'a Entry> for proto::Entry {
6022    fn from(entry: &'a Entry) -> Self {
6023        Self {
6024            id: entry.id.to_proto(),
6025            is_dir: entry.is_dir(),
6026            path: entry.path.to_string_lossy().into(),
6027            inode: entry.inode,
6028            mtime: entry.mtime.map(|time| time.into()),
6029            is_ignored: entry.is_ignored,
6030            is_external: entry.is_external,
6031            is_fifo: entry.is_fifo,
6032            size: Some(entry.size),
6033            canonical_path: entry
6034                .canonical_path
6035                .as_ref()
6036                .map(|path| path.to_string_lossy().to_string()),
6037        }
6038    }
6039}
6040
6041impl<'a> TryFrom<(&'a CharBag, &PathMatcher, proto::Entry)> for Entry {
6042    type Error = anyhow::Error;
6043
6044    fn try_from(
6045        (root_char_bag, always_included, entry): (&'a CharBag, &PathMatcher, proto::Entry),
6046    ) -> Result<Self> {
6047        let kind = if entry.is_dir {
6048            EntryKind::Dir
6049        } else {
6050            EntryKind::File
6051        };
6052        let path: Arc<Path> = PathBuf::from(entry.path).into();
6053        let char_bag = char_bag_for_path(*root_char_bag, &path);
6054        Ok(Entry {
6055            id: ProjectEntryId::from_proto(entry.id),
6056            kind,
6057            path: path.clone(),
6058            inode: entry.inode,
6059            mtime: entry.mtime.map(|time| time.into()),
6060            size: entry.size.unwrap_or(0),
6061            canonical_path: entry
6062                .canonical_path
6063                .map(|path_string| Box::from(Path::new(&path_string))),
6064            is_ignored: entry.is_ignored,
6065            is_always_included: always_included.is_match(path.as_ref()),
6066            is_external: entry.is_external,
6067            is_private: false,
6068            char_bag,
6069            is_fifo: entry.is_fifo,
6070        })
6071    }
6072}
6073
6074fn status_from_proto(
6075    simple_status: i32,
6076    status: Option<proto::GitFileStatus>,
6077) -> anyhow::Result<FileStatus> {
6078    use proto::git_file_status::Variant;
6079
6080    let Some(variant) = status.and_then(|status| status.variant) else {
6081        let code = proto::GitStatus::from_i32(simple_status)
6082            .ok_or_else(|| anyhow!("Invalid git status code: {simple_status}"))?;
6083        let result = match code {
6084            proto::GitStatus::Added => TrackedStatus {
6085                worktree_status: StatusCode::Added,
6086                index_status: StatusCode::Unmodified,
6087            }
6088            .into(),
6089            proto::GitStatus::Modified => TrackedStatus {
6090                worktree_status: StatusCode::Modified,
6091                index_status: StatusCode::Unmodified,
6092            }
6093            .into(),
6094            proto::GitStatus::Conflict => UnmergedStatus {
6095                first_head: UnmergedStatusCode::Updated,
6096                second_head: UnmergedStatusCode::Updated,
6097            }
6098            .into(),
6099            proto::GitStatus::Deleted => TrackedStatus {
6100                worktree_status: StatusCode::Deleted,
6101                index_status: StatusCode::Unmodified,
6102            }
6103            .into(),
6104            _ => return Err(anyhow!("Invalid code for simple status: {simple_status}")),
6105        };
6106        return Ok(result);
6107    };
6108
6109    let result = match variant {
6110        Variant::Untracked(_) => FileStatus::Untracked,
6111        Variant::Ignored(_) => FileStatus::Ignored,
6112        Variant::Unmerged(unmerged) => {
6113            let [first_head, second_head] =
6114                [unmerged.first_head, unmerged.second_head].map(|head| {
6115                    let code = proto::GitStatus::from_i32(head)
6116                        .ok_or_else(|| anyhow!("Invalid git status code: {head}"))?;
6117                    let result = match code {
6118                        proto::GitStatus::Added => UnmergedStatusCode::Added,
6119                        proto::GitStatus::Updated => UnmergedStatusCode::Updated,
6120                        proto::GitStatus::Deleted => UnmergedStatusCode::Deleted,
6121                        _ => return Err(anyhow!("Invalid code for unmerged status: {code:?}")),
6122                    };
6123                    Ok(result)
6124                });
6125            let [first_head, second_head] = [first_head?, second_head?];
6126            UnmergedStatus {
6127                first_head,
6128                second_head,
6129            }
6130            .into()
6131        }
6132        Variant::Tracked(tracked) => {
6133            let [index_status, worktree_status] = [tracked.index_status, tracked.worktree_status]
6134                .map(|status| {
6135                    let code = proto::GitStatus::from_i32(status)
6136                        .ok_or_else(|| anyhow!("Invalid git status code: {status}"))?;
6137                    let result = match code {
6138                        proto::GitStatus::Modified => StatusCode::Modified,
6139                        proto::GitStatus::TypeChanged => StatusCode::TypeChanged,
6140                        proto::GitStatus::Added => StatusCode::Added,
6141                        proto::GitStatus::Deleted => StatusCode::Deleted,
6142                        proto::GitStatus::Renamed => StatusCode::Renamed,
6143                        proto::GitStatus::Copied => StatusCode::Copied,
6144                        proto::GitStatus::Unmodified => StatusCode::Unmodified,
6145                        _ => return Err(anyhow!("Invalid code for tracked status: {code:?}")),
6146                    };
6147                    Ok(result)
6148                });
6149            let [index_status, worktree_status] = [index_status?, worktree_status?];
6150            TrackedStatus {
6151                index_status,
6152                worktree_status,
6153            }
6154            .into()
6155        }
6156    };
6157    Ok(result)
6158}
6159
6160fn status_to_proto(status: FileStatus) -> proto::GitFileStatus {
6161    use proto::git_file_status::{Tracked, Unmerged, Variant};
6162
6163    let variant = match status {
6164        FileStatus::Untracked => Variant::Untracked(Default::default()),
6165        FileStatus::Ignored => Variant::Ignored(Default::default()),
6166        FileStatus::Unmerged(UnmergedStatus {
6167            first_head,
6168            second_head,
6169        }) => Variant::Unmerged(Unmerged {
6170            first_head: unmerged_status_to_proto(first_head),
6171            second_head: unmerged_status_to_proto(second_head),
6172        }),
6173        FileStatus::Tracked(TrackedStatus {
6174            index_status,
6175            worktree_status,
6176        }) => Variant::Tracked(Tracked {
6177            index_status: tracked_status_to_proto(index_status),
6178            worktree_status: tracked_status_to_proto(worktree_status),
6179        }),
6180    };
6181    proto::GitFileStatus {
6182        variant: Some(variant),
6183    }
6184}
6185
6186fn unmerged_status_to_proto(code: UnmergedStatusCode) -> i32 {
6187    match code {
6188        UnmergedStatusCode::Added => proto::GitStatus::Added as _,
6189        UnmergedStatusCode::Deleted => proto::GitStatus::Deleted as _,
6190        UnmergedStatusCode::Updated => proto::GitStatus::Updated as _,
6191    }
6192}
6193
6194fn tracked_status_to_proto(code: StatusCode) -> i32 {
6195    match code {
6196        StatusCode::Added => proto::GitStatus::Added as _,
6197        StatusCode::Deleted => proto::GitStatus::Deleted as _,
6198        StatusCode::Modified => proto::GitStatus::Modified as _,
6199        StatusCode::Renamed => proto::GitStatus::Renamed as _,
6200        StatusCode::TypeChanged => proto::GitStatus::TypeChanged as _,
6201        StatusCode::Copied => proto::GitStatus::Copied as _,
6202        StatusCode::Unmodified => proto::GitStatus::Unmodified as _,
6203    }
6204}
6205
6206#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
6207pub struct ProjectEntryId(usize);
6208
6209impl ProjectEntryId {
6210    pub const MAX: Self = Self(usize::MAX);
6211    pub const MIN: Self = Self(usize::MIN);
6212
6213    pub fn new(counter: &AtomicUsize) -> Self {
6214        Self(counter.fetch_add(1, SeqCst))
6215    }
6216
6217    pub fn from_proto(id: u64) -> Self {
6218        Self(id as usize)
6219    }
6220
6221    pub fn to_proto(&self) -> u64 {
6222        self.0 as u64
6223    }
6224
6225    pub fn to_usize(&self) -> usize {
6226        self.0
6227    }
6228}
6229
6230#[cfg(any(test, feature = "test-support"))]
6231impl CreatedEntry {
6232    pub fn to_included(self) -> Option<Entry> {
6233        match self {
6234            CreatedEntry::Included(entry) => Some(entry),
6235            CreatedEntry::Excluded { .. } => None,
6236        }
6237    }
6238}