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        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2443            let abs_path = self.absolutize(&entry.path);
2444            match smol::block_on(build_gitignore(&abs_path, fs)) {
2445                Ok(ignore) => {
2446                    self.ignores_by_parent_abs_path
2447                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2448                }
2449                Err(error) => {
2450                    log::error!(
2451                        "error loading .gitignore file {:?} - {:?}",
2452                        &entry.path,
2453                        error
2454                    );
2455                }
2456            }
2457        }
2458
2459        if entry.kind == EntryKind::PendingDir
2460            && let Some(existing_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), ())
2461        {
2462            entry.kind = existing_entry.kind;
2463        }
2464
2465        let scan_id = self.scan_id;
2466        let removed = self.entries_by_path.insert_or_replace(entry.clone(), ());
2467        if let Some(removed) = removed
2468            && removed.id != entry.id
2469        {
2470            self.entries_by_id.remove(&removed.id, ());
2471        }
2472        self.entries_by_id.insert_or_replace(
2473            PathEntry {
2474                id: entry.id,
2475                path: entry.path.clone(),
2476                is_ignored: entry.is_ignored,
2477                scan_id,
2478            },
2479            (),
2480        );
2481
2482        entry
2483    }
2484
2485    fn ancestor_inodes_for_path(&self, path: &RelPath) -> TreeSet<u64> {
2486        let mut inodes = TreeSet::default();
2487        for ancestor in path.ancestors().skip(1) {
2488            if let Some(entry) = self.entry_for_path(ancestor) {
2489                inodes.insert(entry.inode);
2490            }
2491        }
2492        inodes
2493    }
2494
2495    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool, fs: &dyn Fs) -> IgnoreStack {
2496        let mut new_ignores = Vec::new();
2497        let mut repo_root = None;
2498        for (index, ancestor) in abs_path.ancestors().enumerate() {
2499            if index > 0 {
2500                if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2501                    new_ignores.push((ancestor, Some(ignore.clone())));
2502                } else {
2503                    new_ignores.push((ancestor, None));
2504                }
2505            }
2506            let metadata = smol::block_on(fs.metadata(&ancestor.join(DOT_GIT)))
2507                .ok()
2508                .flatten();
2509            if metadata.is_some() {
2510                repo_root = Some(Arc::from(ancestor));
2511                break;
2512            }
2513        }
2514
2515        let mut ignore_stack = if let Some(global_gitignore) = self.global_gitignore.clone() {
2516            IgnoreStack::global(global_gitignore)
2517        } else {
2518            IgnoreStack::none()
2519        };
2520        ignore_stack.repo_root = repo_root;
2521        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2522            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2523                ignore_stack = IgnoreStack::all();
2524                break;
2525            } else if let Some(ignore) = ignore {
2526                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2527            }
2528        }
2529
2530        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2531            ignore_stack = IgnoreStack::all();
2532        }
2533
2534        ignore_stack
2535    }
2536
2537    #[cfg(test)]
2538    fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2539        self.entries_by_path
2540            .cursor::<()>(())
2541            .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2542    }
2543
2544    #[cfg(test)]
2545    pub fn check_invariants(&self, git_state: bool) {
2546        use pretty_assertions::assert_eq;
2547
2548        assert_eq!(
2549            self.entries_by_path
2550                .cursor::<()>(())
2551                .map(|e| (&e.path, e.id))
2552                .collect::<Vec<_>>(),
2553            self.entries_by_id
2554                .cursor::<()>(())
2555                .map(|e| (&e.path, e.id))
2556                .collect::<collections::BTreeSet<_>>()
2557                .into_iter()
2558                .collect::<Vec<_>>(),
2559            "entries_by_path and entries_by_id are inconsistent"
2560        );
2561
2562        let mut files = self.files(true, 0);
2563        let mut visible_files = self.files(false, 0);
2564        for entry in self.entries_by_path.cursor::<()>(()) {
2565            if entry.is_file() {
2566                assert_eq!(files.next().unwrap().inode, entry.inode);
2567                if (!entry.is_ignored && !entry.is_external) || entry.is_always_included {
2568                    assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2569                }
2570            }
2571        }
2572
2573        assert!(files.next().is_none());
2574        assert!(visible_files.next().is_none());
2575
2576        let mut bfs_paths = Vec::new();
2577        let mut stack = self
2578            .root_entry()
2579            .map(|e| e.path.as_ref())
2580            .into_iter()
2581            .collect::<Vec<_>>();
2582        while let Some(path) = stack.pop() {
2583            bfs_paths.push(path);
2584            let ix = stack.len();
2585            for child_entry in self.child_entries(path) {
2586                stack.insert(ix, &child_entry.path);
2587            }
2588        }
2589
2590        let dfs_paths_via_iter = self
2591            .entries_by_path
2592            .cursor::<()>(())
2593            .map(|e| e.path.as_ref())
2594            .collect::<Vec<_>>();
2595        assert_eq!(bfs_paths, dfs_paths_via_iter);
2596
2597        let dfs_paths_via_traversal = self
2598            .entries(true, 0)
2599            .map(|e| e.path.as_ref())
2600            .collect::<Vec<_>>();
2601
2602        assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2603
2604        if git_state {
2605            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2606                let ignore_parent_path = &RelPath::new(
2607                    ignore_parent_abs_path
2608                        .strip_prefix(self.abs_path.as_path())
2609                        .unwrap(),
2610                    PathStyle::local(),
2611                )
2612                .unwrap();
2613                assert!(self.entry_for_path(ignore_parent_path).is_some());
2614                assert!(
2615                    self.entry_for_path(
2616                        &ignore_parent_path.join(RelPath::unix(GITIGNORE).unwrap())
2617                    )
2618                    .is_some()
2619                );
2620            }
2621        }
2622    }
2623
2624    #[cfg(test)]
2625    pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&RelPath, u64, bool)> {
2626        let mut paths = Vec::new();
2627        for entry in self.entries_by_path.cursor::<()>(()) {
2628            if include_ignored || !entry.is_ignored {
2629                paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2630            }
2631        }
2632        paths.sort_by(|a, b| a.0.cmp(b.0));
2633        paths
2634    }
2635}
2636
2637impl BackgroundScannerState {
2638    fn should_scan_directory(&self, entry: &Entry) -> bool {
2639        (!entry.is_external && (!entry.is_ignored || entry.is_always_included))
2640            || entry.path.file_name() == Some(DOT_GIT)
2641            || entry.path.file_name() == Some(local_settings_folder_name())
2642            || entry.path.file_name() == Some(local_vscode_folder_name())
2643            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2644            || self
2645                .paths_to_scan
2646                .iter()
2647                .any(|p| p.starts_with(&entry.path))
2648            || self
2649                .path_prefixes_to_scan
2650                .iter()
2651                .any(|p| entry.path.starts_with(p))
2652    }
2653
2654    fn enqueue_scan_dir(
2655        &self,
2656        abs_path: Arc<Path>,
2657        entry: &Entry,
2658        scan_job_tx: &Sender<ScanJob>,
2659        fs: &dyn Fs,
2660    ) {
2661        let path = entry.path.clone();
2662        let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true, fs);
2663        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2664
2665        if !ancestor_inodes.contains(&entry.inode) {
2666            ancestor_inodes.insert(entry.inode);
2667            scan_job_tx
2668                .try_send(ScanJob {
2669                    abs_path,
2670                    path,
2671                    ignore_stack,
2672                    scan_queue: scan_job_tx.clone(),
2673                    ancestor_inodes,
2674                    is_external: entry.is_external,
2675                    is_hidden: entry.is_hidden,
2676                })
2677                .unwrap();
2678        }
2679    }
2680
2681    fn reuse_entry_id(&mut self, entry: &mut Entry) {
2682        if let Some(mtime) = entry.mtime {
2683            // If an entry with the same inode was removed from the worktree during this scan,
2684            // then it *might* represent the same file or directory. But the OS might also have
2685            // re-used the inode for a completely different file or directory.
2686            //
2687            // Conditionally reuse the old entry's id:
2688            // * if the mtime is the same, the file was probably been renamed.
2689            // * if the path is the same, the file may just have been updated
2690            if let Some(removed_entry) = self.removed_entries.remove(&entry.inode) {
2691                if removed_entry.mtime == Some(mtime) || removed_entry.path == entry.path {
2692                    entry.id = removed_entry.id;
2693                }
2694            } else if let Some(existing_entry) = self.snapshot.entry_for_path(&entry.path) {
2695                entry.id = existing_entry.id;
2696            }
2697        }
2698    }
2699
2700    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs, watcher: &dyn Watcher) -> Entry {
2701        self.reuse_entry_id(&mut entry);
2702        let entry = self.snapshot.insert_entry(entry, fs);
2703        if entry.path.file_name() == Some(&DOT_GIT) {
2704            self.insert_git_repository(entry.path.clone(), fs, watcher);
2705        }
2706
2707        #[cfg(test)]
2708        self.snapshot.check_invariants(false);
2709
2710        entry
2711    }
2712
2713    fn populate_dir(
2714        &mut self,
2715        parent_path: Arc<RelPath>,
2716        entries: impl IntoIterator<Item = Entry>,
2717        ignore: Option<Arc<Gitignore>>,
2718    ) {
2719        let mut parent_entry = if let Some(parent_entry) = self
2720            .snapshot
2721            .entries_by_path
2722            .get(&PathKey(parent_path.clone()), ())
2723        {
2724            parent_entry.clone()
2725        } else {
2726            log::warn!(
2727                "populating a directory {:?} that has been removed",
2728                parent_path
2729            );
2730            return;
2731        };
2732
2733        match parent_entry.kind {
2734            EntryKind::PendingDir | EntryKind::UnloadedDir => parent_entry.kind = EntryKind::Dir,
2735            EntryKind::Dir => {}
2736            _ => return,
2737        }
2738
2739        if let Some(ignore) = ignore {
2740            let abs_parent_path = self
2741                .snapshot
2742                .abs_path
2743                .as_path()
2744                .join(parent_path.as_std_path())
2745                .into();
2746            self.snapshot
2747                .ignores_by_parent_abs_path
2748                .insert(abs_parent_path, (ignore, false));
2749        }
2750
2751        let parent_entry_id = parent_entry.id;
2752        self.scanned_dirs.insert(parent_entry_id);
2753        let mut entries_by_path_edits = vec![Edit::Insert(parent_entry)];
2754        let mut entries_by_id_edits = Vec::new();
2755
2756        for entry in entries {
2757            entries_by_id_edits.push(Edit::Insert(PathEntry {
2758                id: entry.id,
2759                path: entry.path.clone(),
2760                is_ignored: entry.is_ignored,
2761                scan_id: self.snapshot.scan_id,
2762            }));
2763            entries_by_path_edits.push(Edit::Insert(entry));
2764        }
2765
2766        self.snapshot
2767            .entries_by_path
2768            .edit(entries_by_path_edits, ());
2769        self.snapshot.entries_by_id.edit(entries_by_id_edits, ());
2770
2771        if let Err(ix) = self.changed_paths.binary_search(&parent_path) {
2772            self.changed_paths.insert(ix, parent_path.clone());
2773        }
2774
2775        #[cfg(test)]
2776        self.snapshot.check_invariants(false);
2777    }
2778
2779    fn remove_path(&mut self, path: &RelPath) {
2780        log::trace!("background scanner removing path {path:?}");
2781        let mut new_entries;
2782        let removed_entries;
2783        {
2784            let mut cursor = self
2785                .snapshot
2786                .entries_by_path
2787                .cursor::<TraversalProgress>(());
2788            new_entries = cursor.slice(&TraversalTarget::path(path), Bias::Left);
2789            removed_entries = cursor.slice(&TraversalTarget::successor(path), Bias::Left);
2790            new_entries.append(cursor.suffix(), ());
2791        }
2792        self.snapshot.entries_by_path = new_entries;
2793
2794        let mut removed_ids = Vec::with_capacity(removed_entries.summary().count);
2795        for entry in removed_entries.cursor::<()>(()) {
2796            match self.removed_entries.entry(entry.inode) {
2797                hash_map::Entry::Occupied(mut e) => {
2798                    let prev_removed_entry = e.get_mut();
2799                    if entry.id > prev_removed_entry.id {
2800                        *prev_removed_entry = entry.clone();
2801                    }
2802                }
2803                hash_map::Entry::Vacant(e) => {
2804                    e.insert(entry.clone());
2805                }
2806            }
2807
2808            if entry.path.file_name() == Some(GITIGNORE) {
2809                let abs_parent_path = self.snapshot.absolutize(&entry.path.parent().unwrap());
2810                if let Some((_, needs_update)) = self
2811                    .snapshot
2812                    .ignores_by_parent_abs_path
2813                    .get_mut(abs_parent_path.as_path())
2814                {
2815                    *needs_update = true;
2816                }
2817            }
2818
2819            if let Err(ix) = removed_ids.binary_search(&entry.id) {
2820                removed_ids.insert(ix, entry.id);
2821            }
2822        }
2823
2824        self.snapshot
2825            .entries_by_id
2826            .edit(removed_ids.iter().map(|&id| Edit::Remove(id)).collect(), ());
2827        self.snapshot
2828            .git_repositories
2829            .retain(|id, _| removed_ids.binary_search(id).is_err());
2830
2831        #[cfg(test)]
2832        self.snapshot.check_invariants(false);
2833    }
2834
2835    fn insert_git_repository(
2836        &mut self,
2837        dot_git_path: Arc<RelPath>,
2838        fs: &dyn Fs,
2839        watcher: &dyn Watcher,
2840    ) {
2841        let work_dir_path: Arc<RelPath> = match dot_git_path.parent() {
2842            Some(parent_dir) => {
2843                // Guard against repositories inside the repository metadata
2844                if parent_dir
2845                    .components()
2846                    .any(|component| component == DOT_GIT)
2847                {
2848                    log::debug!(
2849                        "not building git repository for nested `.git` directory, `.git` path in the worktree: {dot_git_path:?}"
2850                    );
2851                    return;
2852                };
2853
2854                parent_dir.into()
2855            }
2856            None => {
2857                // `dot_git_path.parent().is_none()` means `.git` directory is the opened worktree itself,
2858                // no files inside that directory are tracked by git, so no need to build the repo around it
2859                log::debug!(
2860                    "not building git repository for the worktree itself, `.git` path in the worktree: {dot_git_path:?}"
2861                );
2862                return;
2863            }
2864        };
2865
2866        let dot_git_abs_path = Arc::from(self.snapshot.absolutize(&dot_git_path).as_ref());
2867
2868        self.insert_git_repository_for_path(
2869            WorkDirectory::InProject {
2870                relative_path: work_dir_path,
2871            },
2872            dot_git_abs_path,
2873            fs,
2874            watcher,
2875        )
2876        .log_err();
2877    }
2878
2879    fn insert_git_repository_for_path(
2880        &mut self,
2881        work_directory: WorkDirectory,
2882        dot_git_abs_path: Arc<Path>,
2883        fs: &dyn Fs,
2884        watcher: &dyn Watcher,
2885    ) -> Result<LocalRepositoryEntry> {
2886        let work_dir_entry = self
2887            .snapshot
2888            .entry_for_path(&work_directory.path_key().0)
2889            .with_context(|| {
2890                format!(
2891                    "working directory `{}` not indexed",
2892                    work_directory
2893                        .path_key()
2894                        .0
2895                        .display(self.snapshot.path_style)
2896                )
2897            })?;
2898        let work_directory_abs_path = self.snapshot.work_directory_abs_path(&work_directory);
2899
2900        let (repository_dir_abs_path, common_dir_abs_path) =
2901            discover_git_paths(&dot_git_abs_path, fs);
2902        watcher
2903            .add(&common_dir_abs_path)
2904            .context("failed to add common directory to watcher")
2905            .log_err();
2906        if !repository_dir_abs_path.starts_with(&common_dir_abs_path) {
2907            watcher
2908                .add(&repository_dir_abs_path)
2909                .context("failed to add repository directory to watcher")
2910                .log_err();
2911        }
2912
2913        let work_directory_id = work_dir_entry.id;
2914
2915        let local_repository = LocalRepositoryEntry {
2916            work_directory_id,
2917            work_directory,
2918            work_directory_abs_path: work_directory_abs_path.as_path().into(),
2919            git_dir_scan_id: 0,
2920            dot_git_abs_path,
2921            common_dir_abs_path,
2922            repository_dir_abs_path,
2923        };
2924
2925        self.snapshot
2926            .git_repositories
2927            .insert(work_directory_id, local_repository.clone());
2928
2929        log::trace!("inserting new local git repository");
2930        Ok(local_repository)
2931    }
2932}
2933
2934async fn is_git_dir(path: &Path, fs: &dyn Fs) -> bool {
2935    if let Some(file_name) = path.file_name()
2936        && file_name == DOT_GIT
2937    {
2938        return true;
2939    }
2940
2941    // If we're in a bare repository, we are not inside a `.git` folder. In a
2942    // bare repository, the root folder contains what would normally be in the
2943    // `.git` folder.
2944    let head_metadata = fs.metadata(&path.join("HEAD")).await;
2945    if !matches!(head_metadata, Ok(Some(_))) {
2946        return false;
2947    }
2948    let config_metadata = fs.metadata(&path.join("config")).await;
2949    matches!(config_metadata, Ok(Some(_)))
2950}
2951
2952async fn build_gitignore(abs_path: &Path, fs: &dyn Fs) -> Result<Gitignore> {
2953    let contents = fs
2954        .load(abs_path)
2955        .await
2956        .with_context(|| format!("failed to load gitignore file at {}", abs_path.display()))?;
2957    let parent = abs_path.parent().unwrap_or_else(|| Path::new("/"));
2958    let mut builder = GitignoreBuilder::new(parent);
2959    for line in contents.lines() {
2960        builder.add_line(Some(abs_path.into()), line)?;
2961    }
2962    Ok(builder.build()?)
2963}
2964
2965impl Deref for Worktree {
2966    type Target = Snapshot;
2967
2968    fn deref(&self) -> &Self::Target {
2969        match self {
2970            Worktree::Local(worktree) => &worktree.snapshot,
2971            Worktree::Remote(worktree) => &worktree.snapshot,
2972        }
2973    }
2974}
2975
2976impl Deref for LocalWorktree {
2977    type Target = LocalSnapshot;
2978
2979    fn deref(&self) -> &Self::Target {
2980        &self.snapshot
2981    }
2982}
2983
2984impl Deref for RemoteWorktree {
2985    type Target = Snapshot;
2986
2987    fn deref(&self) -> &Self::Target {
2988        &self.snapshot
2989    }
2990}
2991
2992impl fmt::Debug for LocalWorktree {
2993    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2994        self.snapshot.fmt(f)
2995    }
2996}
2997
2998impl fmt::Debug for Snapshot {
2999    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3000        struct EntriesById<'a>(&'a SumTree<PathEntry>);
3001        struct EntriesByPath<'a>(&'a SumTree<Entry>);
3002
3003        impl fmt::Debug for EntriesByPath<'_> {
3004            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3005                f.debug_map()
3006                    .entries(self.0.iter().map(|entry| (&entry.path, entry.id)))
3007                    .finish()
3008            }
3009        }
3010
3011        impl fmt::Debug for EntriesById<'_> {
3012            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3013                f.debug_list().entries(self.0.iter()).finish()
3014            }
3015        }
3016
3017        f.debug_struct("Snapshot")
3018            .field("id", &self.id)
3019            .field("root_name", &self.root_name)
3020            .field("entries_by_path", &EntriesByPath(&self.entries_by_path))
3021            .field("entries_by_id", &EntriesById(&self.entries_by_id))
3022            .finish()
3023    }
3024}
3025
3026#[derive(Debug, Clone, PartialEq)]
3027pub struct File {
3028    pub worktree: Entity<Worktree>,
3029    pub path: Arc<RelPath>,
3030    pub disk_state: DiskState,
3031    pub entry_id: Option<ProjectEntryId>,
3032    pub is_local: bool,
3033    pub is_private: bool,
3034}
3035
3036impl language::File for File {
3037    fn as_local(&self) -> Option<&dyn language::LocalFile> {
3038        if self.is_local { Some(self) } else { None }
3039    }
3040
3041    fn disk_state(&self) -> DiskState {
3042        self.disk_state
3043    }
3044
3045    fn path(&self) -> &Arc<RelPath> {
3046        &self.path
3047    }
3048
3049    fn full_path(&self, cx: &App) -> PathBuf {
3050        self.worktree.read(cx).full_path(&self.path)
3051    }
3052
3053    /// Returns the last component of this handle's absolute path. If this handle refers to the root
3054    /// of its worktree, then this method will return the name of the worktree itself.
3055    fn file_name<'a>(&'a self, cx: &'a App) -> &'a str {
3056        self.path
3057            .file_name()
3058            .unwrap_or_else(|| self.worktree.read(cx).root_name_str())
3059    }
3060
3061    fn worktree_id(&self, cx: &App) -> WorktreeId {
3062        self.worktree.read(cx).id()
3063    }
3064
3065    fn to_proto(&self, cx: &App) -> rpc::proto::File {
3066        rpc::proto::File {
3067            worktree_id: self.worktree.read(cx).id().to_proto(),
3068            entry_id: self.entry_id.map(|id| id.to_proto()),
3069            path: self.path.as_ref().to_proto(),
3070            mtime: self.disk_state.mtime().map(|time| time.into()),
3071            is_deleted: self.disk_state == DiskState::Deleted,
3072        }
3073    }
3074
3075    fn is_private(&self) -> bool {
3076        self.is_private
3077    }
3078
3079    fn path_style(&self, cx: &App) -> PathStyle {
3080        self.worktree.read(cx).path_style()
3081    }
3082}
3083
3084impl language::LocalFile for File {
3085    fn abs_path(&self, cx: &App) -> PathBuf {
3086        self.worktree.read(cx).absolutize(&self.path)
3087    }
3088
3089    fn load(&self, cx: &App) -> Task<Result<String>> {
3090        let worktree = self.worktree.read(cx).as_local().unwrap();
3091        let abs_path = worktree.absolutize(&self.path);
3092        let fs = worktree.fs.clone();
3093        cx.background_spawn(async move { fs.load(&abs_path).await })
3094    }
3095
3096    fn load_bytes(&self, cx: &App) -> Task<Result<Vec<u8>>> {
3097        let worktree = self.worktree.read(cx).as_local().unwrap();
3098        let abs_path = worktree.absolutize(&self.path);
3099        let fs = worktree.fs.clone();
3100        cx.background_spawn(async move { fs.load_bytes(&abs_path).await })
3101    }
3102}
3103
3104impl File {
3105    pub fn for_entry(entry: Entry, worktree: Entity<Worktree>) -> Arc<Self> {
3106        Arc::new(Self {
3107            worktree,
3108            path: entry.path.clone(),
3109            disk_state: if let Some(mtime) = entry.mtime {
3110                DiskState::Present { mtime }
3111            } else {
3112                DiskState::New
3113            },
3114            entry_id: Some(entry.id),
3115            is_local: true,
3116            is_private: entry.is_private,
3117        })
3118    }
3119
3120    pub fn from_proto(
3121        proto: rpc::proto::File,
3122        worktree: Entity<Worktree>,
3123        cx: &App,
3124    ) -> Result<Self> {
3125        let worktree_id = worktree.read(cx).as_remote().context("not remote")?.id();
3126
3127        anyhow::ensure!(
3128            worktree_id.to_proto() == proto.worktree_id,
3129            "worktree id does not match file"
3130        );
3131
3132        let disk_state = if proto.is_deleted {
3133            DiskState::Deleted
3134        } else if let Some(mtime) = proto.mtime.map(&Into::into) {
3135            DiskState::Present { mtime }
3136        } else {
3137            DiskState::New
3138        };
3139
3140        Ok(Self {
3141            worktree,
3142            path: RelPath::from_proto(&proto.path).context("invalid path in file protobuf")?,
3143            disk_state,
3144            entry_id: proto.entry_id.map(ProjectEntryId::from_proto),
3145            is_local: false,
3146            is_private: false,
3147        })
3148    }
3149
3150    pub fn from_dyn(file: Option<&Arc<dyn language::File>>) -> Option<&Self> {
3151        file.and_then(|f| {
3152            let f: &dyn language::File = f.borrow();
3153            let f: &dyn Any = f;
3154            f.downcast_ref()
3155        })
3156    }
3157
3158    pub fn worktree_id(&self, cx: &App) -> WorktreeId {
3159        self.worktree.read(cx).id()
3160    }
3161
3162    pub fn project_entry_id(&self) -> Option<ProjectEntryId> {
3163        match self.disk_state {
3164            DiskState::Deleted => None,
3165            _ => self.entry_id,
3166        }
3167    }
3168}
3169
3170#[derive(Clone, Debug, PartialEq, Eq)]
3171pub struct Entry {
3172    pub id: ProjectEntryId,
3173    pub kind: EntryKind,
3174    pub path: Arc<RelPath>,
3175    pub inode: u64,
3176    pub mtime: Option<MTime>,
3177
3178    pub canonical_path: Option<Arc<Path>>,
3179    /// Whether this entry is ignored by Git.
3180    ///
3181    /// We only scan ignored entries once the directory is expanded and
3182    /// exclude them from searches.
3183    pub is_ignored: bool,
3184
3185    /// Whether this entry is hidden or inside hidden directory.
3186    ///
3187    /// We only scan hidden entries once the directory is expanded.
3188    pub is_hidden: bool,
3189
3190    /// Whether this entry is always included in searches.
3191    ///
3192    /// This is used for entries that are always included in searches, even
3193    /// if they are ignored by git. Overridden by file_scan_exclusions.
3194    pub is_always_included: bool,
3195
3196    /// Whether this entry's canonical path is outside of the worktree.
3197    /// This means the entry is only accessible from the worktree root via a
3198    /// symlink.
3199    ///
3200    /// We only scan entries outside of the worktree once the symlinked
3201    /// directory is expanded. External entries are treated like gitignored
3202    /// entries in that they are not included in searches.
3203    pub is_external: bool,
3204
3205    /// Whether this entry is considered to be a `.env` file.
3206    pub is_private: bool,
3207    /// The entry's size on disk, in bytes.
3208    pub size: u64,
3209    pub char_bag: CharBag,
3210    pub is_fifo: bool,
3211}
3212
3213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3214pub enum EntryKind {
3215    UnloadedDir,
3216    PendingDir,
3217    Dir,
3218    File,
3219}
3220
3221#[derive(Clone, Copy, Debug, PartialEq)]
3222pub enum PathChange {
3223    /// A filesystem entry was was created.
3224    Added,
3225    /// A filesystem entry was removed.
3226    Removed,
3227    /// A filesystem entry was updated.
3228    Updated,
3229    /// A filesystem entry was either updated or added. We don't know
3230    /// whether or not it already existed, because the path had not
3231    /// been loaded before the event.
3232    AddedOrUpdated,
3233    /// A filesystem entry was found during the initial scan of the worktree.
3234    Loaded,
3235}
3236
3237#[derive(Clone, Debug, PartialEq, Eq)]
3238pub struct UpdatedGitRepository {
3239    /// ID of the repository's working directory.
3240    ///
3241    /// For a repo that's above the worktree root, this is the ID of the worktree root, and hence not unique.
3242    /// It's included here to aid the GitStore in detecting when a repository's working directory is renamed.
3243    pub work_directory_id: ProjectEntryId,
3244    pub old_work_directory_abs_path: Option<Arc<Path>>,
3245    pub new_work_directory_abs_path: Option<Arc<Path>>,
3246    /// For a normal git repository checkout, the absolute path to the .git directory.
3247    /// For a worktree, the absolute path to the worktree's subdirectory inside the .git directory.
3248    pub dot_git_abs_path: Option<Arc<Path>>,
3249    pub repository_dir_abs_path: Option<Arc<Path>>,
3250    pub common_dir_abs_path: Option<Arc<Path>>,
3251}
3252
3253pub type UpdatedEntriesSet = Arc<[(Arc<RelPath>, ProjectEntryId, PathChange)]>;
3254pub type UpdatedGitRepositoriesSet = Arc<[UpdatedGitRepository]>;
3255
3256#[derive(Clone, Debug)]
3257pub struct PathProgress<'a> {
3258    pub max_path: &'a RelPath,
3259}
3260
3261#[derive(Clone, Debug)]
3262pub struct PathSummary<S> {
3263    pub max_path: Arc<RelPath>,
3264    pub item_summary: S,
3265}
3266
3267impl<S: Summary> Summary for PathSummary<S> {
3268    type Context<'a> = S::Context<'a>;
3269
3270    fn zero(cx: Self::Context<'_>) -> Self {
3271        Self {
3272            max_path: RelPath::empty().into(),
3273            item_summary: S::zero(cx),
3274        }
3275    }
3276
3277    fn add_summary(&mut self, rhs: &Self, cx: Self::Context<'_>) {
3278        self.max_path = rhs.max_path.clone();
3279        self.item_summary.add_summary(&rhs.item_summary, cx);
3280    }
3281}
3282
3283impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathProgress<'a> {
3284    fn zero(_: <PathSummary<S> as Summary>::Context<'_>) -> Self {
3285        Self {
3286            max_path: RelPath::empty(),
3287        }
3288    }
3289
3290    fn add_summary(
3291        &mut self,
3292        summary: &'a PathSummary<S>,
3293        _: <PathSummary<S> as Summary>::Context<'_>,
3294    ) {
3295        self.max_path = summary.max_path.as_ref()
3296    }
3297}
3298
3299impl<'a> sum_tree::Dimension<'a, PathSummary<GitSummary>> for GitSummary {
3300    fn zero(_cx: ()) -> Self {
3301        Default::default()
3302    }
3303
3304    fn add_summary(&mut self, summary: &'a PathSummary<GitSummary>, _: ()) {
3305        *self += summary.item_summary
3306    }
3307}
3308
3309impl<'a>
3310    sum_tree::SeekTarget<'a, PathSummary<GitSummary>, Dimensions<TraversalProgress<'a>, GitSummary>>
3311    for PathTarget<'_>
3312{
3313    fn cmp(
3314        &self,
3315        cursor_location: &Dimensions<TraversalProgress<'a>, GitSummary>,
3316        _: (),
3317    ) -> Ordering {
3318        self.cmp_path(cursor_location.0.max_path)
3319    }
3320}
3321
3322impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for PathKey {
3323    fn zero(_: S::Context<'_>) -> Self {
3324        Default::default()
3325    }
3326
3327    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3328        self.0 = summary.max_path.clone();
3329    }
3330}
3331
3332impl<'a, S: Summary> sum_tree::Dimension<'a, PathSummary<S>> for TraversalProgress<'a> {
3333    fn zero(_cx: S::Context<'_>) -> Self {
3334        Default::default()
3335    }
3336
3337    fn add_summary(&mut self, summary: &'a PathSummary<S>, _: S::Context<'_>) {
3338        self.max_path = summary.max_path.as_ref();
3339    }
3340}
3341
3342impl Entry {
3343    fn new(
3344        path: Arc<RelPath>,
3345        metadata: &fs::Metadata,
3346        next_entry_id: &AtomicUsize,
3347        root_char_bag: CharBag,
3348        canonical_path: Option<Arc<Path>>,
3349    ) -> Self {
3350        let char_bag = char_bag_for_path(root_char_bag, &path);
3351        Self {
3352            id: ProjectEntryId::new(next_entry_id),
3353            kind: if metadata.is_dir {
3354                EntryKind::PendingDir
3355            } else {
3356                EntryKind::File
3357            },
3358            path,
3359            inode: metadata.inode,
3360            mtime: Some(metadata.mtime),
3361            size: metadata.len,
3362            canonical_path,
3363            is_ignored: false,
3364            is_hidden: false,
3365            is_always_included: false,
3366            is_external: false,
3367            is_private: false,
3368            char_bag,
3369            is_fifo: metadata.is_fifo,
3370        }
3371    }
3372
3373    pub fn is_created(&self) -> bool {
3374        self.mtime.is_some()
3375    }
3376
3377    pub fn is_dir(&self) -> bool {
3378        self.kind.is_dir()
3379    }
3380
3381    pub fn is_file(&self) -> bool {
3382        self.kind.is_file()
3383    }
3384}
3385
3386impl EntryKind {
3387    pub fn is_dir(&self) -> bool {
3388        matches!(
3389            self,
3390            EntryKind::Dir | EntryKind::PendingDir | EntryKind::UnloadedDir
3391        )
3392    }
3393
3394    pub fn is_unloaded(&self) -> bool {
3395        matches!(self, EntryKind::UnloadedDir)
3396    }
3397
3398    pub fn is_file(&self) -> bool {
3399        matches!(self, EntryKind::File)
3400    }
3401}
3402
3403impl sum_tree::Item for Entry {
3404    type Summary = EntrySummary;
3405
3406    fn summary(&self, _cx: ()) -> Self::Summary {
3407        let non_ignored_count = if (self.is_ignored || self.is_external) && !self.is_always_included
3408        {
3409            0
3410        } else {
3411            1
3412        };
3413        let file_count;
3414        let non_ignored_file_count;
3415        if self.is_file() {
3416            file_count = 1;
3417            non_ignored_file_count = non_ignored_count;
3418        } else {
3419            file_count = 0;
3420            non_ignored_file_count = 0;
3421        }
3422
3423        EntrySummary {
3424            max_path: self.path.clone(),
3425            count: 1,
3426            non_ignored_count,
3427            file_count,
3428            non_ignored_file_count,
3429        }
3430    }
3431}
3432
3433impl sum_tree::KeyedItem for Entry {
3434    type Key = PathKey;
3435
3436    fn key(&self) -> Self::Key {
3437        PathKey(self.path.clone())
3438    }
3439}
3440
3441#[derive(Clone, Debug)]
3442pub struct EntrySummary {
3443    max_path: Arc<RelPath>,
3444    count: usize,
3445    non_ignored_count: usize,
3446    file_count: usize,
3447    non_ignored_file_count: usize,
3448}
3449
3450impl Default for EntrySummary {
3451    fn default() -> Self {
3452        Self {
3453            max_path: Arc::from(RelPath::empty()),
3454            count: 0,
3455            non_ignored_count: 0,
3456            file_count: 0,
3457            non_ignored_file_count: 0,
3458        }
3459    }
3460}
3461
3462impl sum_tree::ContextLessSummary for EntrySummary {
3463    fn zero() -> Self {
3464        Default::default()
3465    }
3466
3467    fn add_summary(&mut self, rhs: &Self) {
3468        self.max_path = rhs.max_path.clone();
3469        self.count += rhs.count;
3470        self.non_ignored_count += rhs.non_ignored_count;
3471        self.file_count += rhs.file_count;
3472        self.non_ignored_file_count += rhs.non_ignored_file_count;
3473    }
3474}
3475
3476#[derive(Clone, Debug)]
3477struct PathEntry {
3478    id: ProjectEntryId,
3479    path: Arc<RelPath>,
3480    is_ignored: bool,
3481    scan_id: usize,
3482}
3483
3484impl sum_tree::Item for PathEntry {
3485    type Summary = PathEntrySummary;
3486
3487    fn summary(&self, _cx: ()) -> Self::Summary {
3488        PathEntrySummary { max_id: self.id }
3489    }
3490}
3491
3492impl sum_tree::KeyedItem for PathEntry {
3493    type Key = ProjectEntryId;
3494
3495    fn key(&self) -> Self::Key {
3496        self.id
3497    }
3498}
3499
3500#[derive(Clone, Debug, Default)]
3501struct PathEntrySummary {
3502    max_id: ProjectEntryId,
3503}
3504
3505impl sum_tree::ContextLessSummary for PathEntrySummary {
3506    fn zero() -> Self {
3507        Default::default()
3508    }
3509
3510    fn add_summary(&mut self, summary: &Self) {
3511        self.max_id = summary.max_id;
3512    }
3513}
3514
3515impl<'a> sum_tree::Dimension<'a, PathEntrySummary> for ProjectEntryId {
3516    fn zero(_cx: ()) -> Self {
3517        Default::default()
3518    }
3519
3520    fn add_summary(&mut self, summary: &'a PathEntrySummary, _: ()) {
3521        *self = summary.max_id;
3522    }
3523}
3524
3525#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
3526pub struct PathKey(pub Arc<RelPath>);
3527
3528impl Default for PathKey {
3529    fn default() -> Self {
3530        Self(RelPath::empty().into())
3531    }
3532}
3533
3534impl<'a> sum_tree::Dimension<'a, EntrySummary> for PathKey {
3535    fn zero(_cx: ()) -> Self {
3536        Default::default()
3537    }
3538
3539    fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
3540        self.0 = summary.max_path.clone();
3541    }
3542}
3543
3544struct BackgroundScanner {
3545    state: Mutex<BackgroundScannerState>,
3546    fs: Arc<dyn Fs>,
3547    fs_case_sensitive: bool,
3548    status_updates_tx: UnboundedSender<ScanState>,
3549    executor: BackgroundExecutor,
3550    scan_requests_rx: channel::Receiver<ScanRequest>,
3551    path_prefixes_to_scan_rx: channel::Receiver<PathPrefixScanRequest>,
3552    next_entry_id: Arc<AtomicUsize>,
3553    phase: BackgroundScannerPhase,
3554    watcher: Arc<dyn Watcher>,
3555    settings: WorktreeSettings,
3556    share_private_files: bool,
3557}
3558
3559#[derive(Copy, Clone, PartialEq)]
3560enum BackgroundScannerPhase {
3561    InitialScan,
3562    EventsReceivedDuringInitialScan,
3563    Events,
3564}
3565
3566impl BackgroundScanner {
3567    async fn run(&mut self, mut fs_events_rx: Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>) {
3568        // If the worktree root does not contain a git repository, then find
3569        // the git repository in an ancestor directory. Find any gitignore files
3570        // in ancestor directories.
3571        let root_abs_path = self.state.lock().snapshot.abs_path.clone();
3572        let (ignores, repo) = discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await;
3573        self.state
3574            .lock()
3575            .snapshot
3576            .ignores_by_parent_abs_path
3577            .extend(ignores);
3578        let containing_git_repository = repo.and_then(|(ancestor_dot_git, work_directory)| {
3579            self.state
3580                .lock()
3581                .insert_git_repository_for_path(
3582                    work_directory,
3583                    ancestor_dot_git.clone().into(),
3584                    self.fs.as_ref(),
3585                    self.watcher.as_ref(),
3586                )
3587                .log_err()?;
3588            Some(ancestor_dot_git)
3589        });
3590
3591        log::trace!("containing git repository: {containing_git_repository:?}");
3592
3593        let mut global_gitignore_events =
3594            if let Some(global_gitignore_path) = &paths::global_gitignore_path() {
3595                self.state.lock().snapshot.global_gitignore =
3596                    if self.fs.is_file(&global_gitignore_path).await {
3597                        build_gitignore(global_gitignore_path, self.fs.as_ref())
3598                            .await
3599                            .ok()
3600                            .map(Arc::new)
3601                    } else {
3602                        None
3603                    };
3604                self.fs
3605                    .watch(global_gitignore_path, FS_WATCH_LATENCY)
3606                    .await
3607                    .0
3608            } else {
3609                self.state.lock().snapshot.global_gitignore = None;
3610                Box::pin(futures::stream::empty())
3611            };
3612
3613        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3614        {
3615            let mut state = self.state.lock();
3616            state.snapshot.scan_id += 1;
3617            if let Some(mut root_entry) = state.snapshot.root_entry().cloned() {
3618                let ignore_stack = state.snapshot.ignore_stack_for_abs_path(
3619                    root_abs_path.as_path(),
3620                    true,
3621                    self.fs.as_ref(),
3622                );
3623                if ignore_stack.is_abs_path_ignored(root_abs_path.as_path(), true) {
3624                    root_entry.is_ignored = true;
3625                    state.insert_entry(root_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
3626                }
3627                if root_entry.is_dir() {
3628                    state.enqueue_scan_dir(
3629                        root_abs_path.as_path().into(),
3630                        &root_entry,
3631                        &scan_job_tx,
3632                        self.fs.as_ref(),
3633                    );
3634                }
3635            }
3636        };
3637
3638        // Perform an initial scan of the directory.
3639        drop(scan_job_tx);
3640        self.scan_dirs(true, scan_job_rx).await;
3641        {
3642            let mut state = self.state.lock();
3643            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3644        }
3645
3646        self.send_status_update(false, SmallVec::new());
3647
3648        // Process any any FS events that occurred while performing the initial scan.
3649        // For these events, update events cannot be as precise, because we didn't
3650        // have the previous state loaded yet.
3651        self.phase = BackgroundScannerPhase::EventsReceivedDuringInitialScan;
3652        if let Poll::Ready(Some(mut paths)) = futures::poll!(fs_events_rx.next()) {
3653            while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3654                paths.extend(more_paths);
3655            }
3656            self.process_events(
3657                paths
3658                    .into_iter()
3659                    .filter(|e| e.kind.is_some())
3660                    .map(Into::into)
3661                    .collect(),
3662            )
3663            .await;
3664        }
3665        if let Some(abs_path) = containing_git_repository {
3666            self.process_events(vec![abs_path]).await;
3667        }
3668
3669        // Continue processing events until the worktree is dropped.
3670        self.phase = BackgroundScannerPhase::Events;
3671
3672        loop {
3673            select_biased! {
3674                // Process any path refresh requests from the worktree. Prioritize
3675                // these before handling changes reported by the filesystem.
3676                request = self.next_scan_request().fuse() => {
3677                    let Ok(request) = request else { break };
3678                    if !self.process_scan_request(request, false).await {
3679                        return;
3680                    }
3681                }
3682
3683                path_prefix_request = self.path_prefixes_to_scan_rx.recv().fuse() => {
3684                    let Ok(request) = path_prefix_request else { break };
3685                    log::trace!("adding path prefix {:?}", request.path);
3686
3687                    let did_scan = self.forcibly_load_paths(std::slice::from_ref(&request.path)).await;
3688                    if did_scan {
3689                        let abs_path =
3690                        {
3691                            let mut state = self.state.lock();
3692                            state.path_prefixes_to_scan.insert(request.path.clone());
3693                            state.snapshot.absolutize(&request.path)
3694                        };
3695
3696                        if let Some(abs_path) = self.fs.canonicalize(&abs_path).await.log_err() {
3697                            self.process_events(vec![abs_path]).await;
3698                        }
3699                    }
3700                    self.send_status_update(false, request.done);
3701                }
3702
3703                paths = fs_events_rx.next().fuse() => {
3704                    let Some(mut paths) = paths else { break };
3705                    while let Poll::Ready(Some(more_paths)) = futures::poll!(fs_events_rx.next()) {
3706                        paths.extend(more_paths);
3707                    }
3708                    self.process_events(paths.into_iter().filter(|e| e.kind.is_some()).map(Into::into).collect()).await;
3709                }
3710
3711                paths = global_gitignore_events.next().fuse() => {
3712                    match paths.as_deref() {
3713                        Some([event, ..]) => {
3714                            self.update_global_gitignore(&event.path).await;
3715                        }
3716                        _ => {},
3717                    }
3718                }
3719            }
3720        }
3721    }
3722
3723    async fn process_scan_request(&self, mut request: ScanRequest, scanning: bool) -> bool {
3724        log::debug!("rescanning paths {:?}", request.relative_paths);
3725
3726        request.relative_paths.sort_unstable();
3727        self.forcibly_load_paths(&request.relative_paths).await;
3728
3729        let root_path = self.state.lock().snapshot.abs_path.clone();
3730        let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
3731        let root_canonical_path = match &root_canonical_path {
3732            Ok(path) => SanitizedPath::new(path),
3733            Err(err) => {
3734                log::error!("failed to canonicalize root path {root_path:?}: {err}");
3735                return true;
3736            }
3737        };
3738        let abs_paths = request
3739            .relative_paths
3740            .iter()
3741            .map(|path| {
3742                if path.file_name().is_some() {
3743                    root_canonical_path.as_path().join(path.as_std_path())
3744                } else {
3745                    root_canonical_path.as_path().to_path_buf()
3746                }
3747            })
3748            .collect::<Vec<_>>();
3749
3750        {
3751            let mut state = self.state.lock();
3752            let is_idle = state.snapshot.completed_scan_id == state.snapshot.scan_id;
3753            state.snapshot.scan_id += 1;
3754            if is_idle {
3755                state.snapshot.completed_scan_id = state.snapshot.scan_id;
3756            }
3757        }
3758
3759        self.reload_entries_for_paths(
3760            &root_path,
3761            &root_canonical_path,
3762            &request.relative_paths,
3763            abs_paths,
3764            None,
3765        )
3766        .await;
3767
3768        self.send_status_update(scanning, request.done)
3769    }
3770
3771    async fn process_events(&self, mut abs_paths: Vec<PathBuf>) {
3772        let root_path = self.state.lock().snapshot.abs_path.clone();
3773        let root_canonical_path = self.fs.canonicalize(root_path.as_path()).await;
3774        let root_canonical_path = match &root_canonical_path {
3775            Ok(path) => SanitizedPath::new(path),
3776            Err(err) => {
3777                let new_path = self
3778                    .state
3779                    .lock()
3780                    .snapshot
3781                    .root_file_handle
3782                    .clone()
3783                    .and_then(|handle| handle.current_path(&self.fs).log_err())
3784                    .map(|path| SanitizedPath::new_arc(&path))
3785                    .filter(|new_path| *new_path != root_path);
3786
3787                if let Some(new_path) = new_path {
3788                    log::info!(
3789                        "root renamed from {} to {}",
3790                        root_path.as_path().display(),
3791                        new_path.as_path().display()
3792                    );
3793                    self.status_updates_tx
3794                        .unbounded_send(ScanState::RootUpdated { new_path })
3795                        .ok();
3796                } else {
3797                    log::warn!("root path could not be canonicalized: {}", err);
3798                }
3799                return;
3800            }
3801        };
3802
3803        // Certain directories may have FS changes, but do not lead to git data changes that Zed cares about.
3804        // Ignore these, to avoid Zed unnecessarily rescanning git metadata.
3805        let skipped_files_in_dot_git = [COMMIT_MESSAGE, INDEX_LOCK];
3806        let skipped_dirs_in_dot_git = [FSMONITOR_DAEMON, LFS_DIR];
3807
3808        let mut relative_paths = Vec::with_capacity(abs_paths.len());
3809        let mut dot_git_abs_paths = Vec::new();
3810        abs_paths.sort_unstable();
3811        abs_paths.dedup_by(|a, b| a.starts_with(b));
3812        abs_paths.retain(|abs_path| {
3813            let abs_path = &SanitizedPath::new(abs_path);
3814
3815            let snapshot = &self.state.lock().snapshot;
3816            {
3817                let mut is_git_related = false;
3818
3819                let dot_git_paths = abs_path.as_path().ancestors().find_map(|ancestor| {
3820                    if smol::block_on(is_git_dir(ancestor, self.fs.as_ref())) {
3821                        let path_in_git_dir = abs_path
3822                            .as_path()
3823                            .strip_prefix(ancestor)
3824                            .expect("stripping off the ancestor");
3825                        Some((ancestor.to_owned(), path_in_git_dir.to_owned()))
3826                    } else {
3827                        None
3828                    }
3829                });
3830
3831                if let Some((dot_git_abs_path, path_in_git_dir)) = dot_git_paths {
3832                    if skipped_files_in_dot_git
3833                        .iter()
3834                        .any(|skipped| OsStr::new(skipped) == path_in_git_dir.as_path().as_os_str())
3835                        || skipped_dirs_in_dot_git.iter().any(|skipped_git_subdir| {
3836                            path_in_git_dir.starts_with(skipped_git_subdir)
3837                        })
3838                    {
3839                        log::debug!("ignoring event {abs_path:?} as it's in the .git directory among skipped files or directories");
3840                        return false;
3841                    }
3842
3843                    is_git_related = true;
3844                    if !dot_git_abs_paths.contains(&dot_git_abs_path) {
3845                        dot_git_abs_paths.push(dot_git_abs_path);
3846                    }
3847                }
3848
3849                let relative_path = if let Ok(path) =
3850                    abs_path.strip_prefix(&root_canonical_path)
3851                    && let Ok(path) = RelPath::new(path, PathStyle::local())
3852                {
3853                    path
3854                } else {
3855                    if is_git_related {
3856                        log::debug!(
3857                            "ignoring event {abs_path:?}, since it's in git dir outside of root path {root_canonical_path:?}",
3858                        );
3859                    } else {
3860                        log::error!(
3861                          "ignoring event {abs_path:?} outside of root path {root_canonical_path:?}",
3862                        );
3863                    }
3864                    return false;
3865                };
3866
3867                if abs_path.file_name() == Some(OsStr::new(GITIGNORE)) {
3868                    for (_, repo) in snapshot
3869                        .git_repositories
3870                        .iter()
3871                        .filter(|(_, repo)| repo.directory_contains(&relative_path))
3872                    {
3873                        if !dot_git_abs_paths.iter().any(|dot_git_abs_path| {
3874                            dot_git_abs_path == repo.common_dir_abs_path.as_ref()
3875                        }) {
3876                            dot_git_abs_paths.push(repo.common_dir_abs_path.to_path_buf());
3877                        }
3878                    }
3879                }
3880
3881                let parent_dir_is_loaded = relative_path.parent().is_none_or(|parent| {
3882                    snapshot
3883                        .entry_for_path(parent)
3884                        .is_some_and(|entry| entry.kind == EntryKind::Dir)
3885                });
3886                if !parent_dir_is_loaded {
3887                    log::debug!("ignoring event {relative_path:?} within unloaded directory");
3888                    return false;
3889                }
3890
3891                if self.settings.is_path_excluded(&relative_path) {
3892                    if !is_git_related {
3893                        log::debug!("ignoring FS event for excluded path {relative_path:?}");
3894                    }
3895                    return false;
3896                }
3897
3898                relative_paths.push(relative_path.into_arc());
3899                true
3900            }
3901        });
3902
3903        if relative_paths.is_empty() && dot_git_abs_paths.is_empty() {
3904            return;
3905        }
3906
3907        self.state.lock().snapshot.scan_id += 1;
3908
3909        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3910        log::debug!("received fs events {:?}", relative_paths);
3911        self.reload_entries_for_paths(
3912            &root_path,
3913            &root_canonical_path,
3914            &relative_paths,
3915            abs_paths,
3916            Some(scan_job_tx.clone()),
3917        )
3918        .await;
3919
3920        let affected_repo_roots = if !dot_git_abs_paths.is_empty() {
3921            self.update_git_repositories(dot_git_abs_paths)
3922        } else {
3923            Vec::new()
3924        };
3925
3926        {
3927            let mut ignores_to_update = self.ignores_needing_update();
3928            ignores_to_update.extend(affected_repo_roots);
3929            let ignores_to_update = self.order_ignores(ignores_to_update);
3930            let snapshot = self.state.lock().snapshot.clone();
3931            self.update_ignore_statuses_for_paths(scan_job_tx, snapshot, ignores_to_update)
3932                .await;
3933            self.scan_dirs(false, scan_job_rx).await;
3934        }
3935
3936        {
3937            let mut state = self.state.lock();
3938            state.snapshot.completed_scan_id = state.snapshot.scan_id;
3939            for (_, entry) in mem::take(&mut state.removed_entries) {
3940                state.scanned_dirs.remove(&entry.id);
3941            }
3942        }
3943        self.send_status_update(false, SmallVec::new());
3944    }
3945
3946    async fn update_global_gitignore(&self, abs_path: &Path) {
3947        let ignore = build_gitignore(abs_path, self.fs.as_ref())
3948            .await
3949            .log_err()
3950            .map(Arc::new);
3951        let (prev_snapshot, ignore_stack, abs_path) = {
3952            let mut state = self.state.lock();
3953            state.snapshot.global_gitignore = ignore;
3954            let abs_path = state.snapshot.abs_path().clone();
3955            let ignore_stack =
3956                state
3957                    .snapshot
3958                    .ignore_stack_for_abs_path(&abs_path, true, self.fs.as_ref());
3959            (state.snapshot.clone(), ignore_stack, abs_path)
3960        };
3961        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3962        self.update_ignore_statuses_for_paths(
3963            scan_job_tx,
3964            prev_snapshot,
3965            vec![(abs_path, ignore_stack)].into_iter(),
3966        )
3967        .await;
3968        self.scan_dirs(false, scan_job_rx).await;
3969        self.send_status_update(false, SmallVec::new());
3970    }
3971
3972    async fn forcibly_load_paths(&self, paths: &[Arc<RelPath>]) -> bool {
3973        let (scan_job_tx, scan_job_rx) = channel::unbounded();
3974        {
3975            let mut state = self.state.lock();
3976            let root_path = state.snapshot.abs_path.clone();
3977            for path in paths {
3978                for ancestor in path.ancestors() {
3979                    if let Some(entry) = state.snapshot.entry_for_path(ancestor)
3980                        && entry.kind == EntryKind::UnloadedDir
3981                    {
3982                        let abs_path = root_path.join(ancestor.as_std_path());
3983                        state.enqueue_scan_dir(
3984                            abs_path.into(),
3985                            entry,
3986                            &scan_job_tx,
3987                            self.fs.as_ref(),
3988                        );
3989                        state.paths_to_scan.insert(path.clone());
3990                        break;
3991                    }
3992                }
3993            }
3994            drop(scan_job_tx);
3995        }
3996        while let Ok(job) = scan_job_rx.recv().await {
3997            self.scan_dir(&job).await.log_err();
3998        }
3999
4000        !mem::take(&mut self.state.lock().paths_to_scan).is_empty()
4001    }
4002
4003    async fn scan_dirs(
4004        &self,
4005        enable_progress_updates: bool,
4006        scan_jobs_rx: channel::Receiver<ScanJob>,
4007    ) {
4008        if self
4009            .status_updates_tx
4010            .unbounded_send(ScanState::Started)
4011            .is_err()
4012        {
4013            return;
4014        }
4015
4016        let progress_update_count = AtomicUsize::new(0);
4017        self.executor
4018            .scoped(|scope| {
4019                for _ in 0..self.executor.num_cpus() {
4020                    scope.spawn(async {
4021                        let mut last_progress_update_count = 0;
4022                        let progress_update_timer = self.progress_timer(enable_progress_updates).fuse();
4023                        futures::pin_mut!(progress_update_timer);
4024
4025                        loop {
4026                            select_biased! {
4027                                // Process any path refresh requests before moving on to process
4028                                // the scan queue, so that user operations are prioritized.
4029                                request = self.next_scan_request().fuse() => {
4030                                    let Ok(request) = request else { break };
4031                                    if !self.process_scan_request(request, true).await {
4032                                        return;
4033                                    }
4034                                }
4035
4036                                // Send periodic progress updates to the worktree. Use an atomic counter
4037                                // to ensure that only one of the workers sends a progress update after
4038                                // the update interval elapses.
4039                                _ = progress_update_timer => {
4040                                    match progress_update_count.compare_exchange(
4041                                        last_progress_update_count,
4042                                        last_progress_update_count + 1,
4043                                        SeqCst,
4044                                        SeqCst
4045                                    ) {
4046                                        Ok(_) => {
4047                                            last_progress_update_count += 1;
4048                                            self.send_status_update(true, SmallVec::new());
4049                                        }
4050                                        Err(count) => {
4051                                            last_progress_update_count = count;
4052                                        }
4053                                    }
4054                                    progress_update_timer.set(self.progress_timer(enable_progress_updates).fuse());
4055                                }
4056
4057                                // Recursively load directories from the file system.
4058                                job = scan_jobs_rx.recv().fuse() => {
4059                                    let Ok(job) = job else { break };
4060                                    if let Err(err) = self.scan_dir(&job).await
4061                                        && job.path.is_empty() {
4062                                            log::error!("error scanning directory {:?}: {}", job.abs_path, err);
4063                                        }
4064                                }
4065                            }
4066                        }
4067                    });
4068                }
4069            })
4070            .await;
4071    }
4072
4073    fn send_status_update(&self, scanning: bool, barrier: SmallVec<[barrier::Sender; 1]>) -> bool {
4074        let mut state = self.state.lock();
4075        if state.changed_paths.is_empty() && scanning {
4076            return true;
4077        }
4078
4079        let new_snapshot = state.snapshot.clone();
4080        let old_snapshot = mem::replace(&mut state.prev_snapshot, new_snapshot.snapshot.clone());
4081        let changes = build_diff(
4082            self.phase,
4083            &old_snapshot,
4084            &new_snapshot,
4085            &state.changed_paths,
4086        );
4087        state.changed_paths.clear();
4088
4089        self.status_updates_tx
4090            .unbounded_send(ScanState::Updated {
4091                snapshot: new_snapshot,
4092                changes,
4093                scanning,
4094                barrier,
4095            })
4096            .is_ok()
4097    }
4098
4099    async fn scan_dir(&self, job: &ScanJob) -> Result<()> {
4100        let root_abs_path;
4101        let root_char_bag;
4102        {
4103            let snapshot = &self.state.lock().snapshot;
4104            if self.settings.is_path_excluded(&job.path) {
4105                log::error!("skipping excluded directory {:?}", job.path);
4106                return Ok(());
4107            }
4108            log::trace!("scanning directory {:?}", job.path);
4109            root_abs_path = snapshot.abs_path().clone();
4110            root_char_bag = snapshot.root_char_bag;
4111        }
4112
4113        let next_entry_id = self.next_entry_id.clone();
4114        let mut ignore_stack = job.ignore_stack.clone();
4115        let mut new_ignore = None;
4116        let mut root_canonical_path = None;
4117        let mut new_entries: Vec<Entry> = Vec::new();
4118        let mut new_jobs: Vec<Option<ScanJob>> = Vec::new();
4119        let mut child_paths = self
4120            .fs
4121            .read_dir(&job.abs_path)
4122            .await?
4123            .filter_map(|entry| async {
4124                match entry {
4125                    Ok(entry) => Some(entry),
4126                    Err(error) => {
4127                        log::error!("error processing entry {:?}", error);
4128                        None
4129                    }
4130                }
4131            })
4132            .collect::<Vec<_>>()
4133            .await;
4134
4135        // Ensure that .git and .gitignore are processed first.
4136        swap_to_front(&mut child_paths, GITIGNORE);
4137        swap_to_front(&mut child_paths, DOT_GIT);
4138
4139        if let Some(path) = child_paths.first()
4140            && path.ends_with(DOT_GIT)
4141        {
4142            ignore_stack.repo_root = Some(job.abs_path.clone());
4143        }
4144
4145        for child_abs_path in child_paths {
4146            let child_abs_path: Arc<Path> = child_abs_path.into();
4147            let child_name = child_abs_path.file_name().unwrap();
4148            let Some(child_path) = child_name
4149                .to_str()
4150                .and_then(|name| Some(job.path.join(RelPath::unix(name).ok()?)))
4151            else {
4152                continue;
4153            };
4154
4155            if child_name == DOT_GIT {
4156                let mut state = self.state.lock();
4157                state.insert_git_repository(
4158                    child_path.clone(),
4159                    self.fs.as_ref(),
4160                    self.watcher.as_ref(),
4161                );
4162            } else if child_name == GITIGNORE {
4163                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
4164                    Ok(ignore) => {
4165                        let ignore = Arc::new(ignore);
4166                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4167                        new_ignore = Some(ignore);
4168                    }
4169                    Err(error) => {
4170                        log::error!(
4171                            "error loading .gitignore file {:?} - {:?}",
4172                            child_name,
4173                            error
4174                        );
4175                    }
4176                }
4177            }
4178
4179            if self.settings.is_path_excluded(&child_path) {
4180                log::debug!("skipping excluded child entry {child_path:?}");
4181                self.state.lock().remove_path(&child_path);
4182                continue;
4183            }
4184
4185            let child_metadata = match self.fs.metadata(&child_abs_path).await {
4186                Ok(Some(metadata)) => metadata,
4187                Ok(None) => continue,
4188                Err(err) => {
4189                    log::error!("error processing {child_abs_path:?}: {err:?}");
4190                    continue;
4191                }
4192            };
4193
4194            let mut child_entry = Entry::new(
4195                child_path.clone(),
4196                &child_metadata,
4197                &next_entry_id,
4198                root_char_bag,
4199                None,
4200            );
4201
4202            if job.is_external {
4203                child_entry.is_external = true;
4204            } else if child_metadata.is_symlink {
4205                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
4206                    Ok(path) => path,
4207                    Err(err) => {
4208                        log::error!("error reading target of symlink {child_abs_path:?}: {err:#}",);
4209                        continue;
4210                    }
4211                };
4212
4213                // lazily canonicalize the root path in order to determine if
4214                // symlinks point outside of the worktree.
4215                let root_canonical_path = match &root_canonical_path {
4216                    Some(path) => path,
4217                    None => match self.fs.canonicalize(&root_abs_path).await {
4218                        Ok(path) => root_canonical_path.insert(path),
4219                        Err(err) => {
4220                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
4221                            continue;
4222                        }
4223                    },
4224                };
4225
4226                if !canonical_path.starts_with(root_canonical_path) {
4227                    child_entry.is_external = true;
4228                }
4229
4230                child_entry.canonical_path = Some(canonical_path.into());
4231            }
4232
4233            child_entry.is_hidden = job.is_hidden
4234                || child_name
4235                    .to_str()
4236                    .map_or(false, |name| is_path_hidden(name));
4237
4238            if child_entry.is_dir() {
4239                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
4240                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4241
4242                // Avoid recursing until crash in the case of a recursive symlink
4243                if job.ancestor_inodes.contains(&child_entry.inode) {
4244                    new_jobs.push(None);
4245                } else {
4246                    let mut ancestor_inodes = job.ancestor_inodes.clone();
4247                    ancestor_inodes.insert(child_entry.inode);
4248
4249                    new_jobs.push(Some(ScanJob {
4250                        abs_path: child_abs_path.clone(),
4251                        path: child_path,
4252                        is_external: child_entry.is_external,
4253                        is_hidden: child_entry.is_hidden,
4254                        ignore_stack: if child_entry.is_ignored {
4255                            IgnoreStack::all()
4256                        } else {
4257                            ignore_stack.clone()
4258                        },
4259                        ancestor_inodes,
4260                        scan_queue: job.scan_queue.clone(),
4261                    }));
4262                }
4263            } else {
4264                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
4265                child_entry.is_always_included = self.settings.is_path_always_included(&child_path);
4266            }
4267
4268            {
4269                let relative_path = job
4270                    .path
4271                    .join(RelPath::unix(child_name.to_str().unwrap()).unwrap());
4272                if self.is_path_private(&relative_path) {
4273                    log::debug!("detected private file: {relative_path:?}");
4274                    child_entry.is_private = true;
4275                }
4276            }
4277
4278            new_entries.push(child_entry);
4279        }
4280
4281        let mut state = self.state.lock();
4282
4283        // Identify any subdirectories that should not be scanned.
4284        let mut job_ix = 0;
4285        for entry in &mut new_entries {
4286            state.reuse_entry_id(entry);
4287            if entry.is_dir() {
4288                if state.should_scan_directory(entry) {
4289                    job_ix += 1;
4290                } else {
4291                    log::debug!("defer scanning directory {:?}", entry.path);
4292                    entry.kind = EntryKind::UnloadedDir;
4293                    new_jobs.remove(job_ix);
4294                }
4295            }
4296            if entry.is_always_included {
4297                state
4298                    .snapshot
4299                    .always_included_entries
4300                    .push(entry.path.clone());
4301            }
4302        }
4303
4304        state.populate_dir(job.path.clone(), new_entries, new_ignore);
4305        self.watcher.add(job.abs_path.as_ref()).log_err();
4306
4307        for new_job in new_jobs.into_iter().flatten() {
4308            job.scan_queue
4309                .try_send(new_job)
4310                .expect("channel is unbounded");
4311        }
4312
4313        Ok(())
4314    }
4315
4316    /// All list arguments should be sorted before calling this function
4317    async fn reload_entries_for_paths(
4318        &self,
4319        root_abs_path: &SanitizedPath,
4320        root_canonical_path: &SanitizedPath,
4321        relative_paths: &[Arc<RelPath>],
4322        abs_paths: Vec<PathBuf>,
4323        scan_queue_tx: Option<Sender<ScanJob>>,
4324    ) {
4325        // grab metadata for all requested paths
4326        let metadata = futures::future::join_all(
4327            abs_paths
4328                .iter()
4329                .map(|abs_path| async move {
4330                    let metadata = self.fs.metadata(abs_path).await?;
4331                    if let Some(metadata) = metadata {
4332                        let canonical_path = self.fs.canonicalize(abs_path).await?;
4333
4334                        // If we're on a case-insensitive filesystem (default on macOS), we want
4335                        // to only ignore metadata for non-symlink files if their absolute-path matches
4336                        // the canonical-path.
4337                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4338                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
4339                        // treated as removed.
4340                        if !self.fs_case_sensitive && !metadata.is_symlink {
4341                            let canonical_file_name = canonical_path.file_name();
4342                            let file_name = abs_path.file_name();
4343                            if canonical_file_name != file_name {
4344                                return Ok(None);
4345                            }
4346                        }
4347
4348                        anyhow::Ok(Some((metadata, SanitizedPath::new_arc(&canonical_path))))
4349                    } else {
4350                        Ok(None)
4351                    }
4352                })
4353                .collect::<Vec<_>>(),
4354        )
4355        .await;
4356
4357        let mut new_ancestor_repo = if relative_paths.iter().any(|path| path.is_empty()) {
4358            Some(discover_ancestor_git_repo(self.fs.clone(), &root_abs_path).await)
4359        } else {
4360            None
4361        };
4362
4363        let mut state = self.state.lock();
4364        let doing_recursive_update = scan_queue_tx.is_some();
4365
4366        // Remove any entries for paths that no longer exist or are being recursively
4367        // refreshed. Do this before adding any new entries, so that renames can be
4368        // detected regardless of the order of the paths.
4369        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4370            if matches!(metadata, Ok(None)) || doing_recursive_update {
4371                log::trace!("remove path {:?}", path);
4372                state.remove_path(path);
4373            }
4374        }
4375
4376        for (path, metadata) in relative_paths.iter().zip(metadata.into_iter()) {
4377            let abs_path: Arc<Path> = root_abs_path.join(path.as_std_path()).into();
4378            match metadata {
4379                Ok(Some((metadata, canonical_path))) => {
4380                    let ignore_stack = state.snapshot.ignore_stack_for_abs_path(
4381                        &abs_path,
4382                        metadata.is_dir,
4383                        self.fs.as_ref(),
4384                    );
4385                    let is_external = !canonical_path.starts_with(&root_canonical_path);
4386                    let mut fs_entry = Entry::new(
4387                        path.clone(),
4388                        &metadata,
4389                        self.next_entry_id.as_ref(),
4390                        state.snapshot.root_char_bag,
4391                        if metadata.is_symlink {
4392                            Some(canonical_path.as_path().to_path_buf().into())
4393                        } else {
4394                            None
4395                        },
4396                    );
4397
4398                    let is_dir = fs_entry.is_dir();
4399                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4400                    fs_entry.is_external = is_external;
4401                    fs_entry.is_private = self.is_path_private(path);
4402                    fs_entry.is_always_included = self.settings.is_path_always_included(path);
4403
4404                    let parent_is_hidden = path
4405                        .parent()
4406                        .and_then(|parent| state.snapshot.entry_for_path(parent))
4407                        .map_or(false, |parent_entry| parent_entry.is_hidden);
4408                    fs_entry.is_hidden = parent_is_hidden
4409                        || path.file_name().map_or(false, |name| is_path_hidden(name));
4410
4411                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, is_dir) {
4412                        if state.should_scan_directory(&fs_entry)
4413                            || (fs_entry.path.is_empty()
4414                                && abs_path.file_name() == Some(OsStr::new(DOT_GIT)))
4415                        {
4416                            state.enqueue_scan_dir(
4417                                abs_path,
4418                                &fs_entry,
4419                                scan_queue_tx,
4420                                self.fs.as_ref(),
4421                            );
4422                        } else {
4423                            fs_entry.kind = EntryKind::UnloadedDir;
4424                        }
4425                    }
4426
4427                    state.insert_entry(fs_entry.clone(), self.fs.as_ref(), self.watcher.as_ref());
4428
4429                    if path.is_empty()
4430                        && let Some((ignores, repo)) = new_ancestor_repo.take()
4431                    {
4432                        log::trace!("updating ancestor git repository");
4433                        state.snapshot.ignores_by_parent_abs_path.extend(ignores);
4434                        if let Some((ancestor_dot_git, work_directory)) = repo {
4435                            state
4436                                .insert_git_repository_for_path(
4437                                    work_directory,
4438                                    ancestor_dot_git.into(),
4439                                    self.fs.as_ref(),
4440                                    self.watcher.as_ref(),
4441                                )
4442                                .log_err();
4443                        }
4444                    }
4445                }
4446                Ok(None) => {
4447                    self.remove_repo_path(path.clone(), &mut state.snapshot);
4448                }
4449                Err(err) => {
4450                    log::error!("error reading file {abs_path:?} on event: {err:#}");
4451                }
4452            }
4453        }
4454
4455        util::extend_sorted(
4456            &mut state.changed_paths,
4457            relative_paths.iter().cloned(),
4458            usize::MAX,
4459            Ord::cmp,
4460        );
4461    }
4462
4463    fn remove_repo_path(&self, path: Arc<RelPath>, snapshot: &mut LocalSnapshot) -> Option<()> {
4464        if !path.components().any(|component| component == DOT_GIT)
4465            && let Some(local_repo) = snapshot.local_repo_for_work_directory_path(&path)
4466        {
4467            let id = local_repo.work_directory_id;
4468            log::debug!("remove repo path: {:?}", path);
4469            snapshot.git_repositories.remove(&id);
4470            return Some(());
4471        }
4472
4473        Some(())
4474    }
4475
4476    async fn update_ignore_statuses_for_paths(
4477        &self,
4478        scan_job_tx: Sender<ScanJob>,
4479        prev_snapshot: LocalSnapshot,
4480        mut ignores_to_update: impl Iterator<Item = (Arc<Path>, IgnoreStack)>,
4481    ) {
4482        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4483        {
4484            while let Some((parent_abs_path, ignore_stack)) = ignores_to_update.next() {
4485                ignore_queue_tx
4486                    .send_blocking(UpdateIgnoreStatusJob {
4487                        abs_path: parent_abs_path,
4488                        ignore_stack,
4489                        ignore_queue: ignore_queue_tx.clone(),
4490                        scan_queue: scan_job_tx.clone(),
4491                    })
4492                    .unwrap();
4493            }
4494        }
4495        drop(ignore_queue_tx);
4496
4497        self.executor
4498            .scoped(|scope| {
4499                for _ in 0..self.executor.num_cpus() {
4500                    scope.spawn(async {
4501                        loop {
4502                            select_biased! {
4503                                // Process any path refresh requests before moving on to process
4504                                // the queue of ignore statuses.
4505                                request = self.next_scan_request().fuse() => {
4506                                    let Ok(request) = request else { break };
4507                                    if !self.process_scan_request(request, true).await {
4508                                        return;
4509                                    }
4510                                }
4511
4512                                // Recursively process directories whose ignores have changed.
4513                                job = ignore_queue_rx.recv().fuse() => {
4514                                    let Ok(job) = job else { break };
4515                                    self.update_ignore_status(job, &prev_snapshot).await;
4516                                }
4517                            }
4518                        }
4519                    });
4520                }
4521            })
4522            .await;
4523    }
4524
4525    fn ignores_needing_update(&self) -> Vec<Arc<Path>> {
4526        let mut ignores_to_update = Vec::new();
4527
4528        {
4529            let snapshot = &mut self.state.lock().snapshot;
4530            let abs_path = snapshot.abs_path.clone();
4531            snapshot
4532                .ignores_by_parent_abs_path
4533                .retain(|parent_abs_path, (_, needs_update)| {
4534                    if let Ok(parent_path) = parent_abs_path.strip_prefix(abs_path.as_path())
4535                        && let Some(parent_path) =
4536                            RelPath::new(&parent_path, PathStyle::local()).log_err()
4537                    {
4538                        if *needs_update {
4539                            *needs_update = false;
4540                            if snapshot.snapshot.entry_for_path(&parent_path).is_some() {
4541                                ignores_to_update.push(parent_abs_path.clone());
4542                            }
4543                        }
4544
4545                        let ignore_path = parent_path.join(RelPath::unix(GITIGNORE).unwrap());
4546                        if snapshot.snapshot.entry_for_path(&ignore_path).is_none() {
4547                            return false;
4548                        }
4549                    }
4550                    true
4551                });
4552        }
4553
4554        ignores_to_update
4555    }
4556
4557    fn order_ignores(
4558        &self,
4559        mut ignores: Vec<Arc<Path>>,
4560    ) -> impl use<> + Iterator<Item = (Arc<Path>, IgnoreStack)> {
4561        let fs = self.fs.clone();
4562        let snapshot = self.state.lock().snapshot.clone();
4563        ignores.sort_unstable();
4564        let mut ignores_to_update = ignores.into_iter().peekable();
4565        std::iter::from_fn(move || {
4566            let parent_abs_path = ignores_to_update.next()?;
4567            while ignores_to_update
4568                .peek()
4569                .map_or(false, |p| p.starts_with(&parent_abs_path))
4570            {
4571                ignores_to_update.next().unwrap();
4572            }
4573            let ignore_stack =
4574                snapshot.ignore_stack_for_abs_path(&parent_abs_path, true, fs.as_ref());
4575            Some((parent_abs_path, ignore_stack))
4576        })
4577    }
4578
4579    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4580        log::trace!("update ignore status {:?}", job.abs_path);
4581
4582        let mut ignore_stack = job.ignore_stack;
4583        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4584            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4585        }
4586
4587        let mut entries_by_id_edits = Vec::new();
4588        let mut entries_by_path_edits = Vec::new();
4589        let Some(path) = job
4590            .abs_path
4591            .strip_prefix(snapshot.abs_path.as_path())
4592            .map_err(|_| {
4593                anyhow::anyhow!(
4594                    "Failed to strip prefix '{}' from path '{}'",
4595                    snapshot.abs_path.as_path().display(),
4596                    job.abs_path.display()
4597                )
4598            })
4599            .log_err()
4600        else {
4601            return;
4602        };
4603
4604        let Some(path) = RelPath::new(&path, PathStyle::local()).log_err() else {
4605            return;
4606        };
4607
4608        if let Ok(Some(metadata)) = smol::block_on(self.fs.metadata(&job.abs_path.join(DOT_GIT)))
4609            && metadata.is_dir
4610        {
4611            ignore_stack.repo_root = Some(job.abs_path.clone());
4612        }
4613
4614        for mut entry in snapshot.child_entries(&path).cloned() {
4615            let was_ignored = entry.is_ignored;
4616            let abs_path: Arc<Path> = snapshot.absolutize(&entry.path).into();
4617            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4618
4619            if entry.is_dir() {
4620                let child_ignore_stack = if entry.is_ignored {
4621                    IgnoreStack::all()
4622                } else {
4623                    ignore_stack.clone()
4624                };
4625
4626                // Scan any directories that were previously ignored and weren't previously scanned.
4627                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4628                    let state = self.state.lock();
4629                    if state.should_scan_directory(&entry) {
4630                        state.enqueue_scan_dir(
4631                            abs_path.clone(),
4632                            &entry,
4633                            &job.scan_queue,
4634                            self.fs.as_ref(),
4635                        );
4636                    }
4637                }
4638
4639                job.ignore_queue
4640                    .send(UpdateIgnoreStatusJob {
4641                        abs_path: abs_path.clone(),
4642                        ignore_stack: child_ignore_stack,
4643                        ignore_queue: job.ignore_queue.clone(),
4644                        scan_queue: job.scan_queue.clone(),
4645                    })
4646                    .await
4647                    .unwrap();
4648            }
4649
4650            if entry.is_ignored != was_ignored {
4651                let mut path_entry = snapshot.entries_by_id.get(&entry.id, ()).unwrap().clone();
4652                path_entry.scan_id = snapshot.scan_id;
4653                path_entry.is_ignored = entry.is_ignored;
4654                entries_by_id_edits.push(Edit::Insert(path_entry));
4655                entries_by_path_edits.push(Edit::Insert(entry));
4656            }
4657        }
4658
4659        let state = &mut self.state.lock();
4660        for edit in &entries_by_path_edits {
4661            if let Edit::Insert(entry) = edit
4662                && let Err(ix) = state.changed_paths.binary_search(&entry.path)
4663            {
4664                state.changed_paths.insert(ix, entry.path.clone());
4665            }
4666        }
4667
4668        state
4669            .snapshot
4670            .entries_by_path
4671            .edit(entries_by_path_edits, ());
4672        state.snapshot.entries_by_id.edit(entries_by_id_edits, ());
4673    }
4674
4675    fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) -> Vec<Arc<Path>> {
4676        log::trace!("reloading repositories: {dot_git_paths:?}");
4677        let mut state = self.state.lock();
4678        let scan_id = state.snapshot.scan_id;
4679        let mut affected_repo_roots = Vec::new();
4680        for dot_git_dir in dot_git_paths {
4681            let existing_repository_entry =
4682                state
4683                    .snapshot
4684                    .git_repositories
4685                    .iter()
4686                    .find_map(|(_, repo)| {
4687                        let dot_git_dir = SanitizedPath::new(&dot_git_dir);
4688                        if SanitizedPath::new(repo.common_dir_abs_path.as_ref()) == dot_git_dir
4689                            || SanitizedPath::new(repo.repository_dir_abs_path.as_ref())
4690                                == dot_git_dir
4691                        {
4692                            Some(repo.clone())
4693                        } else {
4694                            None
4695                        }
4696                    });
4697
4698            match existing_repository_entry {
4699                None => {
4700                    let Ok(relative) = dot_git_dir.strip_prefix(state.snapshot.abs_path()) else {
4701                        debug_panic!(
4702                            "update_git_repositories called with .git directory outside the worktree root"
4703                        );
4704                        return Vec::new();
4705                    };
4706                    affected_repo_roots.push(dot_git_dir.parent().unwrap().into());
4707                    state.insert_git_repository(
4708                        RelPath::new(relative, PathStyle::local())
4709                            .unwrap()
4710                            .into_arc(),
4711                        self.fs.as_ref(),
4712                        self.watcher.as_ref(),
4713                    );
4714                }
4715                Some(local_repository) => {
4716                    state.snapshot.git_repositories.update(
4717                        &local_repository.work_directory_id,
4718                        |entry| {
4719                            entry.git_dir_scan_id = scan_id;
4720                        },
4721                    );
4722                }
4723            };
4724        }
4725
4726        // Remove any git repositories whose .git entry no longer exists.
4727        let snapshot = &mut state.snapshot;
4728        let mut ids_to_preserve = HashSet::default();
4729        for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
4730            let exists_in_snapshot =
4731                snapshot
4732                    .entry_for_id(work_directory_id)
4733                    .is_some_and(|entry| {
4734                        snapshot
4735                            .entry_for_path(&entry.path.join(RelPath::unix(DOT_GIT).unwrap()))
4736                            .is_some()
4737                    });
4738
4739            if exists_in_snapshot
4740                || matches!(
4741                    smol::block_on(self.fs.metadata(&entry.common_dir_abs_path)),
4742                    Ok(Some(_))
4743                )
4744            {
4745                ids_to_preserve.insert(work_directory_id);
4746            }
4747        }
4748
4749        snapshot
4750            .git_repositories
4751            .retain(|work_directory_id, entry| {
4752                let preserve = ids_to_preserve.contains(work_directory_id);
4753                if !preserve {
4754                    affected_repo_roots.push(entry.dot_git_abs_path.parent().unwrap().into());
4755                }
4756                preserve
4757            });
4758
4759        affected_repo_roots
4760    }
4761
4762    async fn progress_timer(&self, running: bool) {
4763        if !running {
4764            return futures::future::pending().await;
4765        }
4766
4767        #[cfg(any(test, feature = "test-support"))]
4768        if self.fs.is_fake() {
4769            return self.executor.simulate_random_delay().await;
4770        }
4771
4772        smol::Timer::after(FS_WATCH_LATENCY).await;
4773    }
4774
4775    fn is_path_private(&self, path: &RelPath) -> bool {
4776        !self.share_private_files && self.settings.is_path_private(path)
4777    }
4778
4779    async fn next_scan_request(&self) -> Result<ScanRequest> {
4780        let mut request = self.scan_requests_rx.recv().await?;
4781        while let Ok(next_request) = self.scan_requests_rx.try_recv() {
4782            request.relative_paths.extend(next_request.relative_paths);
4783            request.done.extend(next_request.done);
4784        }
4785        Ok(request)
4786    }
4787}
4788
4789async fn discover_ancestor_git_repo(
4790    fs: Arc<dyn Fs>,
4791    root_abs_path: &SanitizedPath,
4792) -> (
4793    HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
4794    Option<(PathBuf, WorkDirectory)>,
4795) {
4796    let mut ignores = HashMap::default();
4797    for (index, ancestor) in root_abs_path.as_path().ancestors().enumerate() {
4798        if index != 0 {
4799            if ancestor == paths::home_dir() {
4800                // Unless $HOME is itself the worktree root, don't consider it as a
4801                // containing git repository---expensive and likely unwanted.
4802                break;
4803            } else if let Ok(ignore) = build_gitignore(&ancestor.join(GITIGNORE), fs.as_ref()).await
4804            {
4805                ignores.insert(ancestor.into(), (ignore.into(), false));
4806            }
4807        }
4808
4809        let ancestor_dot_git = ancestor.join(DOT_GIT);
4810        log::trace!("considering ancestor: {ancestor_dot_git:?}");
4811        // Check whether the directory or file called `.git` exists (in the
4812        // case of worktrees it's a file.)
4813        if fs
4814            .metadata(&ancestor_dot_git)
4815            .await
4816            .is_ok_and(|metadata| metadata.is_some())
4817        {
4818            if index != 0 {
4819                // We canonicalize, since the FS events use the canonicalized path.
4820                if let Some(ancestor_dot_git) = fs.canonicalize(&ancestor_dot_git).await.log_err() {
4821                    let location_in_repo = root_abs_path
4822                        .as_path()
4823                        .strip_prefix(ancestor)
4824                        .unwrap()
4825                        .into();
4826                    log::info!("inserting parent git repo for this worktree: {location_in_repo:?}");
4827                    // We associate the external git repo with our root folder and
4828                    // also mark where in the git repo the root folder is located.
4829                    return (
4830                        ignores,
4831                        Some((
4832                            ancestor_dot_git,
4833                            WorkDirectory::AboveProject {
4834                                absolute_path: ancestor.into(),
4835                                location_in_repo,
4836                            },
4837                        )),
4838                    );
4839                };
4840            }
4841
4842            // Reached root of git repository.
4843            break;
4844        }
4845    }
4846
4847    (ignores, None)
4848}
4849
4850fn build_diff(
4851    phase: BackgroundScannerPhase,
4852    old_snapshot: &Snapshot,
4853    new_snapshot: &Snapshot,
4854    event_paths: &[Arc<RelPath>],
4855) -> UpdatedEntriesSet {
4856    use BackgroundScannerPhase::*;
4857    use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4858
4859    // Identify which paths have changed. Use the known set of changed
4860    // parent paths to optimize the search.
4861    let mut changes = Vec::new();
4862    let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>(());
4863    let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>(());
4864    let mut last_newly_loaded_dir_path = None;
4865    old_paths.next();
4866    new_paths.next();
4867    for path in event_paths {
4868        let path = PathKey(path.clone());
4869        if old_paths.item().is_some_and(|e| e.path < path.0) {
4870            old_paths.seek_forward(&path, Bias::Left);
4871        }
4872        if new_paths.item().is_some_and(|e| e.path < path.0) {
4873            new_paths.seek_forward(&path, Bias::Left);
4874        }
4875        loop {
4876            match (old_paths.item(), new_paths.item()) {
4877                (Some(old_entry), Some(new_entry)) => {
4878                    if old_entry.path > path.0
4879                        && new_entry.path > path.0
4880                        && !old_entry.path.starts_with(&path.0)
4881                        && !new_entry.path.starts_with(&path.0)
4882                    {
4883                        break;
4884                    }
4885
4886                    match Ord::cmp(&old_entry.path, &new_entry.path) {
4887                        Ordering::Less => {
4888                            changes.push((old_entry.path.clone(), old_entry.id, Removed));
4889                            old_paths.next();
4890                        }
4891                        Ordering::Equal => {
4892                            if phase == EventsReceivedDuringInitialScan {
4893                                if old_entry.id != new_entry.id {
4894                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
4895                                }
4896                                // If the worktree was not fully initialized when this event was generated,
4897                                // we can't know whether this entry was added during the scan or whether
4898                                // it was merely updated.
4899                                changes.push((
4900                                    new_entry.path.clone(),
4901                                    new_entry.id,
4902                                    AddedOrUpdated,
4903                                ));
4904                            } else if old_entry.id != new_entry.id {
4905                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
4906                                changes.push((new_entry.path.clone(), new_entry.id, Added));
4907                            } else if old_entry != new_entry {
4908                                if old_entry.kind.is_unloaded() {
4909                                    last_newly_loaded_dir_path = Some(&new_entry.path);
4910                                    changes.push((new_entry.path.clone(), new_entry.id, Loaded));
4911                                } else {
4912                                    changes.push((new_entry.path.clone(), new_entry.id, Updated));
4913                                }
4914                            }
4915                            old_paths.next();
4916                            new_paths.next();
4917                        }
4918                        Ordering::Greater => {
4919                            let is_newly_loaded = phase == InitialScan
4920                                || last_newly_loaded_dir_path
4921                                    .as_ref()
4922                                    .is_some_and(|dir| new_entry.path.starts_with(dir));
4923                            changes.push((
4924                                new_entry.path.clone(),
4925                                new_entry.id,
4926                                if is_newly_loaded { Loaded } else { Added },
4927                            ));
4928                            new_paths.next();
4929                        }
4930                    }
4931                }
4932                (Some(old_entry), None) => {
4933                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
4934                    old_paths.next();
4935                }
4936                (None, Some(new_entry)) => {
4937                    let is_newly_loaded = phase == InitialScan
4938                        || last_newly_loaded_dir_path
4939                            .as_ref()
4940                            .is_some_and(|dir| new_entry.path.starts_with(dir));
4941                    changes.push((
4942                        new_entry.path.clone(),
4943                        new_entry.id,
4944                        if is_newly_loaded { Loaded } else { Added },
4945                    ));
4946                    new_paths.next();
4947                }
4948                (None, None) => break,
4949            }
4950        }
4951    }
4952
4953    changes.into()
4954}
4955
4956fn swap_to_front(child_paths: &mut Vec<PathBuf>, file: &str) {
4957    let position = child_paths
4958        .iter()
4959        .position(|path| path.file_name().unwrap() == file);
4960    if let Some(position) = position {
4961        let temp = child_paths.remove(position);
4962        child_paths.insert(0, temp);
4963    }
4964}
4965
4966fn char_bag_for_path(root_char_bag: CharBag, path: &RelPath) -> CharBag {
4967    let mut result = root_char_bag;
4968    result.extend(path.as_unix_str().chars().map(|c| c.to_ascii_lowercase()));
4969    result
4970}
4971
4972fn is_path_hidden(name: &str) -> bool {
4973    name.starts_with('.')
4974}
4975
4976#[derive(Debug)]
4977struct ScanJob {
4978    abs_path: Arc<Path>,
4979    path: Arc<RelPath>,
4980    ignore_stack: IgnoreStack,
4981    scan_queue: Sender<ScanJob>,
4982    ancestor_inodes: TreeSet<u64>,
4983    is_external: bool,
4984    is_hidden: bool,
4985}
4986
4987struct UpdateIgnoreStatusJob {
4988    abs_path: Arc<Path>,
4989    ignore_stack: IgnoreStack,
4990    ignore_queue: Sender<UpdateIgnoreStatusJob>,
4991    scan_queue: Sender<ScanJob>,
4992}
4993
4994pub trait WorktreeModelHandle {
4995    #[cfg(any(test, feature = "test-support"))]
4996    fn flush_fs_events<'a>(
4997        &self,
4998        cx: &'a mut gpui::TestAppContext,
4999    ) -> futures::future::LocalBoxFuture<'a, ()>;
5000
5001    #[cfg(any(test, feature = "test-support"))]
5002    fn flush_fs_events_in_root_git_repository<'a>(
5003        &self,
5004        cx: &'a mut gpui::TestAppContext,
5005    ) -> futures::future::LocalBoxFuture<'a, ()>;
5006}
5007
5008impl WorktreeModelHandle for Entity<Worktree> {
5009    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
5010    // occurred before the worktree was constructed. These events can cause the worktree to perform
5011    // extra directory scans, and emit extra scan-state notifications.
5012    //
5013    // This function mutates the worktree's directory and waits for those mutations to be picked up,
5014    // to ensure that all redundant FS events have already been processed.
5015    #[cfg(any(test, feature = "test-support"))]
5016    fn flush_fs_events<'a>(
5017        &self,
5018        cx: &'a mut gpui::TestAppContext,
5019    ) -> futures::future::LocalBoxFuture<'a, ()> {
5020        let file_name = "fs-event-sentinel";
5021
5022        let tree = self.clone();
5023        let (fs, root_path) = self.read_with(cx, |tree, _| {
5024            let tree = tree.as_local().unwrap();
5025            (tree.fs.clone(), tree.abs_path.clone())
5026        });
5027
5028        async move {
5029            fs.create_file(&root_path.join(file_name), Default::default())
5030                .await
5031                .unwrap();
5032
5033            let mut events = cx.events(&tree);
5034            while events.next().await.is_some() {
5035                if tree.read_with(cx, |tree, _| {
5036                    tree.entry_for_path(RelPath::unix(file_name).unwrap())
5037                        .is_some()
5038                }) {
5039                    break;
5040                }
5041            }
5042
5043            fs.remove_file(&root_path.join(file_name), Default::default())
5044                .await
5045                .unwrap();
5046            while events.next().await.is_some() {
5047                if tree.read_with(cx, |tree, _| {
5048                    tree.entry_for_path(RelPath::unix(file_name).unwrap())
5049                        .is_none()
5050                }) {
5051                    break;
5052                }
5053            }
5054
5055            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5056                .await;
5057        }
5058        .boxed_local()
5059    }
5060
5061    // This function is similar to flush_fs_events, except that it waits for events to be flushed in
5062    // the .git folder of the root repository.
5063    // The reason for its existence is that a repository's .git folder might live *outside* of the
5064    // worktree and thus its FS events might go through a different path.
5065    // In order to flush those, we need to create artificial events in the .git folder and wait
5066    // for the repository to be reloaded.
5067    #[cfg(any(test, feature = "test-support"))]
5068    fn flush_fs_events_in_root_git_repository<'a>(
5069        &self,
5070        cx: &'a mut gpui::TestAppContext,
5071    ) -> futures::future::LocalBoxFuture<'a, ()> {
5072        let file_name = "fs-event-sentinel";
5073
5074        let tree = self.clone();
5075        let (fs, root_path, mut git_dir_scan_id) = self.read_with(cx, |tree, _| {
5076            let tree = tree.as_local().unwrap();
5077            let local_repo_entry = tree
5078                .git_repositories
5079                .values()
5080                .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5081                .unwrap();
5082            (
5083                tree.fs.clone(),
5084                local_repo_entry.common_dir_abs_path.clone(),
5085                local_repo_entry.git_dir_scan_id,
5086            )
5087        });
5088
5089        let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
5090            let tree = tree.as_local().unwrap();
5091            // let repository = tree.repositories.first().unwrap();
5092            let local_repo_entry = tree
5093                .git_repositories
5094                .values()
5095                .min_by_key(|local_repo_entry| local_repo_entry.work_directory.clone())
5096                .unwrap();
5097
5098            if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
5099                *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
5100                true
5101            } else {
5102                false
5103            }
5104        };
5105
5106        async move {
5107            fs.create_file(&root_path.join(file_name), Default::default())
5108                .await
5109                .unwrap();
5110
5111            let mut events = cx.events(&tree);
5112            while events.next().await.is_some() {
5113                if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5114                    break;
5115                }
5116            }
5117
5118            fs.remove_file(&root_path.join(file_name), Default::default())
5119                .await
5120                .unwrap();
5121
5122            while events.next().await.is_some() {
5123                if tree.update(cx, |tree, _| scan_id_increased(tree, &mut git_dir_scan_id)) {
5124                    break;
5125                }
5126            }
5127
5128            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
5129                .await;
5130        }
5131        .boxed_local()
5132    }
5133}
5134
5135#[derive(Clone, Debug)]
5136struct TraversalProgress<'a> {
5137    max_path: &'a RelPath,
5138    count: usize,
5139    non_ignored_count: usize,
5140    file_count: usize,
5141    non_ignored_file_count: usize,
5142}
5143
5144impl TraversalProgress<'_> {
5145    fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
5146        match (include_files, include_dirs, include_ignored) {
5147            (true, true, true) => self.count,
5148            (true, true, false) => self.non_ignored_count,
5149            (true, false, true) => self.file_count,
5150            (true, false, false) => self.non_ignored_file_count,
5151            (false, true, true) => self.count - self.file_count,
5152            (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
5153            (false, false, _) => 0,
5154        }
5155    }
5156}
5157
5158impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
5159    fn zero(_cx: ()) -> Self {
5160        Default::default()
5161    }
5162
5163    fn add_summary(&mut self, summary: &'a EntrySummary, _: ()) {
5164        self.max_path = summary.max_path.as_ref();
5165        self.count += summary.count;
5166        self.non_ignored_count += summary.non_ignored_count;
5167        self.file_count += summary.file_count;
5168        self.non_ignored_file_count += summary.non_ignored_file_count;
5169    }
5170}
5171
5172impl Default for TraversalProgress<'_> {
5173    fn default() -> Self {
5174        Self {
5175            max_path: RelPath::empty(),
5176            count: 0,
5177            non_ignored_count: 0,
5178            file_count: 0,
5179            non_ignored_file_count: 0,
5180        }
5181    }
5182}
5183
5184#[derive(Debug)]
5185pub struct Traversal<'a> {
5186    snapshot: &'a Snapshot,
5187    cursor: sum_tree::Cursor<'a, 'static, Entry, TraversalProgress<'a>>,
5188    include_ignored: bool,
5189    include_files: bool,
5190    include_dirs: bool,
5191}
5192
5193impl<'a> Traversal<'a> {
5194    fn new(
5195        snapshot: &'a Snapshot,
5196        include_files: bool,
5197        include_dirs: bool,
5198        include_ignored: bool,
5199        start_path: &RelPath,
5200    ) -> Self {
5201        let mut cursor = snapshot.entries_by_path.cursor(());
5202        cursor.seek(&TraversalTarget::path(start_path), Bias::Left);
5203        let mut traversal = Self {
5204            snapshot,
5205            cursor,
5206            include_files,
5207            include_dirs,
5208            include_ignored,
5209        };
5210        if traversal.end_offset() == traversal.start_offset() {
5211            traversal.next();
5212        }
5213        traversal
5214    }
5215
5216    pub fn advance(&mut self) -> bool {
5217        self.advance_by(1)
5218    }
5219
5220    pub fn advance_by(&mut self, count: usize) -> bool {
5221        self.cursor.seek_forward(
5222            &TraversalTarget::Count {
5223                count: self.end_offset() + count,
5224                include_dirs: self.include_dirs,
5225                include_files: self.include_files,
5226                include_ignored: self.include_ignored,
5227            },
5228            Bias::Left,
5229        )
5230    }
5231
5232    pub fn advance_to_sibling(&mut self) -> bool {
5233        while let Some(entry) = self.cursor.item() {
5234            self.cursor
5235                .seek_forward(&TraversalTarget::successor(&entry.path), Bias::Left);
5236            if let Some(entry) = self.cursor.item()
5237                && (self.include_files || !entry.is_file())
5238                && (self.include_dirs || !entry.is_dir())
5239                && (self.include_ignored || !entry.is_ignored || entry.is_always_included)
5240            {
5241                return true;
5242            }
5243        }
5244        false
5245    }
5246
5247    pub fn back_to_parent(&mut self) -> bool {
5248        let Some(parent_path) = self.cursor.item().and_then(|entry| entry.path.parent()) else {
5249            return false;
5250        };
5251        self.cursor
5252            .seek(&TraversalTarget::path(parent_path), Bias::Left)
5253    }
5254
5255    pub fn entry(&self) -> Option<&'a Entry> {
5256        self.cursor.item()
5257    }
5258
5259    pub fn snapshot(&self) -> &'a Snapshot {
5260        self.snapshot
5261    }
5262
5263    pub fn start_offset(&self) -> usize {
5264        self.cursor
5265            .start()
5266            .count(self.include_files, self.include_dirs, self.include_ignored)
5267    }
5268
5269    pub fn end_offset(&self) -> usize {
5270        self.cursor
5271            .end()
5272            .count(self.include_files, self.include_dirs, self.include_ignored)
5273    }
5274}
5275
5276impl<'a> Iterator for Traversal<'a> {
5277    type Item = &'a Entry;
5278
5279    fn next(&mut self) -> Option<Self::Item> {
5280        if let Some(item) = self.entry() {
5281            self.advance();
5282            Some(item)
5283        } else {
5284            None
5285        }
5286    }
5287}
5288
5289#[derive(Debug, Clone, Copy)]
5290pub enum PathTarget<'a> {
5291    Path(&'a RelPath),
5292    Successor(&'a RelPath),
5293}
5294
5295impl PathTarget<'_> {
5296    fn cmp_path(&self, other: &RelPath) -> Ordering {
5297        match self {
5298            PathTarget::Path(path) => path.cmp(&other),
5299            PathTarget::Successor(path) => {
5300                if other.starts_with(path) {
5301                    Ordering::Greater
5302                } else {
5303                    Ordering::Equal
5304                }
5305            }
5306        }
5307    }
5308}
5309
5310impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, PathProgress<'a>> for PathTarget<'_> {
5311    fn cmp(&self, cursor_location: &PathProgress<'a>, _: S::Context<'_>) -> Ordering {
5312        self.cmp_path(cursor_location.max_path)
5313    }
5314}
5315
5316impl<'a, S: Summary> SeekTarget<'a, PathSummary<S>, TraversalProgress<'a>> for PathTarget<'_> {
5317    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: S::Context<'_>) -> Ordering {
5318        self.cmp_path(cursor_location.max_path)
5319    }
5320}
5321
5322#[derive(Debug)]
5323enum TraversalTarget<'a> {
5324    Path(PathTarget<'a>),
5325    Count {
5326        count: usize,
5327        include_files: bool,
5328        include_ignored: bool,
5329        include_dirs: bool,
5330    },
5331}
5332
5333impl<'a> TraversalTarget<'a> {
5334    fn path(path: &'a RelPath) -> Self {
5335        Self::Path(PathTarget::Path(path))
5336    }
5337
5338    fn successor(path: &'a RelPath) -> Self {
5339        Self::Path(PathTarget::Successor(path))
5340    }
5341
5342    fn cmp_progress(&self, progress: &TraversalProgress) -> Ordering {
5343        match self {
5344            TraversalTarget::Path(path) => path.cmp_path(progress.max_path),
5345            TraversalTarget::Count {
5346                count,
5347                include_files,
5348                include_dirs,
5349                include_ignored,
5350            } => Ord::cmp(
5351                count,
5352                &progress.count(*include_files, *include_dirs, *include_ignored),
5353            ),
5354        }
5355    }
5356}
5357
5358impl<'a> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'_> {
5359    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5360        self.cmp_progress(cursor_location)
5361    }
5362}
5363
5364impl<'a> SeekTarget<'a, PathSummary<sum_tree::NoSummary>, TraversalProgress<'a>>
5365    for TraversalTarget<'_>
5366{
5367    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: ()) -> Ordering {
5368        self.cmp_progress(cursor_location)
5369    }
5370}
5371
5372pub struct ChildEntriesOptions {
5373    pub include_files: bool,
5374    pub include_dirs: bool,
5375    pub include_ignored: bool,
5376}
5377
5378pub struct ChildEntriesIter<'a> {
5379    parent_path: &'a RelPath,
5380    traversal: Traversal<'a>,
5381}
5382
5383impl<'a> Iterator for ChildEntriesIter<'a> {
5384    type Item = &'a Entry;
5385
5386    fn next(&mut self) -> Option<Self::Item> {
5387        if let Some(item) = self.traversal.entry()
5388            && item.path.starts_with(self.parent_path)
5389        {
5390            self.traversal.advance_to_sibling();
5391            return Some(item);
5392        }
5393        None
5394    }
5395}
5396
5397impl<'a> From<&'a Entry> for proto::Entry {
5398    fn from(entry: &'a Entry) -> Self {
5399        Self {
5400            id: entry.id.to_proto(),
5401            is_dir: entry.is_dir(),
5402            path: entry.path.as_ref().to_proto(),
5403            inode: entry.inode,
5404            mtime: entry.mtime.map(|time| time.into()),
5405            is_ignored: entry.is_ignored,
5406            is_hidden: entry.is_hidden,
5407            is_external: entry.is_external,
5408            is_fifo: entry.is_fifo,
5409            size: Some(entry.size),
5410            canonical_path: entry
5411                .canonical_path
5412                .as_ref()
5413                .map(|path| path.to_string_lossy().into_owned()),
5414        }
5415    }
5416}
5417
5418impl TryFrom<(&CharBag, &PathMatcher, proto::Entry)> for Entry {
5419    type Error = anyhow::Error;
5420
5421    fn try_from(
5422        (root_char_bag, always_included, entry): (&CharBag, &PathMatcher, proto::Entry),
5423    ) -> Result<Self> {
5424        let kind = if entry.is_dir {
5425            EntryKind::Dir
5426        } else {
5427            EntryKind::File
5428        };
5429
5430        let path =
5431            RelPath::from_proto(&entry.path).context("invalid relative path in proto message")?;
5432        let char_bag = char_bag_for_path(*root_char_bag, &path);
5433        let is_always_included = always_included.is_match(path.as_std_path());
5434        Ok(Entry {
5435            id: ProjectEntryId::from_proto(entry.id),
5436            kind,
5437            path,
5438            inode: entry.inode,
5439            mtime: entry.mtime.map(|time| time.into()),
5440            size: entry.size.unwrap_or(0),
5441            canonical_path: entry
5442                .canonical_path
5443                .map(|path_string| Arc::from(PathBuf::from(path_string))),
5444            is_ignored: entry.is_ignored,
5445            is_hidden: entry.is_hidden,
5446            is_always_included,
5447            is_external: entry.is_external,
5448            is_private: false,
5449            char_bag,
5450            is_fifo: entry.is_fifo,
5451        })
5452    }
5453}
5454
5455#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5456pub struct ProjectEntryId(usize);
5457
5458impl ProjectEntryId {
5459    pub const MAX: Self = Self(usize::MAX);
5460    pub const MIN: Self = Self(usize::MIN);
5461
5462    pub fn new(counter: &AtomicUsize) -> Self {
5463        Self(counter.fetch_add(1, SeqCst))
5464    }
5465
5466    pub fn from_proto(id: u64) -> Self {
5467        Self(id as usize)
5468    }
5469
5470    pub fn to_proto(self) -> u64 {
5471        self.0 as u64
5472    }
5473
5474    pub fn from_usize(id: usize) -> Self {
5475        ProjectEntryId(id)
5476    }
5477
5478    pub fn to_usize(self) -> usize {
5479        self.0
5480    }
5481}
5482
5483#[cfg(any(test, feature = "test-support"))]
5484impl CreatedEntry {
5485    pub fn into_included(self) -> Option<Entry> {
5486        match self {
5487            CreatedEntry::Included(entry) => Some(entry),
5488            CreatedEntry::Excluded { .. } => None,
5489        }
5490    }
5491}
5492
5493fn parse_gitfile(content: &str) -> anyhow::Result<&Path> {
5494    let path = content
5495        .strip_prefix("gitdir:")
5496        .with_context(|| format!("parsing gitfile content {content:?}"))?;
5497    Ok(Path::new(path.trim()))
5498}
5499
5500fn discover_git_paths(dot_git_abs_path: &Arc<Path>, fs: &dyn Fs) -> (Arc<Path>, Arc<Path>) {
5501    let mut repository_dir_abs_path = dot_git_abs_path.clone();
5502    let mut common_dir_abs_path = dot_git_abs_path.clone();
5503
5504    if let Some(path) = smol::block_on(fs.load(dot_git_abs_path))
5505        .ok()
5506        .as_ref()
5507        .and_then(|contents| parse_gitfile(contents).log_err())
5508    {
5509        let path = dot_git_abs_path
5510            .parent()
5511            .unwrap_or(Path::new(""))
5512            .join(path);
5513        if let Some(path) = smol::block_on(fs.canonicalize(&path)).log_err() {
5514            repository_dir_abs_path = Path::new(&path).into();
5515            common_dir_abs_path = repository_dir_abs_path.clone();
5516            if let Some(commondir_contents) = smol::block_on(fs.load(&path.join("commondir"))).ok()
5517                && let Some(commondir_path) =
5518                    smol::block_on(fs.canonicalize(&path.join(commondir_contents.trim()))).log_err()
5519            {
5520                common_dir_abs_path = commondir_path.as_path().into();
5521            }
5522        }
5523    };
5524
5525    (repository_dir_abs_path, common_dir_abs_path)
5526}