worktree.rs

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