worktree.rs

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