worktree.rs

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