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