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