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