worktree.rs

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