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