worktree.rs

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