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