worktree.rs

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