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