worktree.rs

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