worktree.rs

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