worktree.rs

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