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