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