worktree.rs

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