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