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