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