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