worktree.rs

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