worktree.rs

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