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