worktree.rs

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