worktree.rs

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