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::{
  25    repository::{GitFileStatus, GitRepository, RepoPath},
  26    DOT_GIT, GITIGNORE,
  27};
  28use gpui::{
  29    AppContext, AsyncAppContext, BackgroundExecutor, Context, EventEmitter, Model, ModelContext,
  30    Task,
  31};
  32use ignore::IgnoreStack;
  33use itertools::Itertools;
  34use language::{
  35    proto::{deserialize_version, serialize_line_ending, serialize_version},
  36    Buffer, Capability, DiagnosticEntry, File as _, LineEnding, PointUtf16, Rope, Unclipped,
  37};
  38use lsp::{DiagnosticSeverity, LanguageServerId};
  39use parking_lot::Mutex;
  40use postage::{
  41    barrier,
  42    prelude::{Sink as _, Stream as _},
  43    watch,
  44};
  45use serde::Serialize;
  46use settings::{Settings, SettingsLocation, SettingsStore};
  47use smol::channel::{self, Sender};
  48use std::time::Instant;
  49use std::{
  50    any::Any,
  51    cmp::{self, Ordering},
  52    convert::TryFrom,
  53    ffi::OsStr,
  54    fmt,
  55    future::Future,
  56    mem,
  57    ops::{AddAssign, Deref, DerefMut, Sub},
  58    path::{Path, PathBuf},
  59    pin::Pin,
  60    sync::{
  61        atomic::{AtomicUsize, Ordering::SeqCst},
  62        Arc,
  63    },
  64    time::{Duration, SystemTime},
  65};
  66use sum_tree::{Bias, Edit, SeekTarget, SumTree, TreeMap, TreeSet};
  67use text::BufferId;
  68use util::{
  69    paths::{PathMatcher, HOME},
  70    ResultExt,
  71};
  72
  73pub use worktree_settings::WorktreeSettings;
  74
  75#[cfg(feature = "test-support")]
  76pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  77#[cfg(not(feature = "test-support"))]
  78pub const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  79
  80const GIT_STATUS_UPDATE_BATCH_SIZE: usize = 100;
  81
  82#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
  83pub struct WorktreeId(usize);
  84
  85/// A set of local or remote files that are being opened as part of a project.
  86/// Responsible for tracking related FS (for local)/collab (for remote) events and corresponding updates.
  87/// Stores git repositories data and the diagnostics for the file(s).
  88///
  89/// Has an absolute path, and may be set to be visible in Zed UI or not.
  90/// May correspond to a directory or a single file.
  91/// Possible examples:
  92/// * a drag and dropped file — may be added as an invisible, "ephemeral" entry to the current worktree
  93/// * a directory opened in Zed — may be added as a visible entry to the current worktree
  94///
  95/// Uses [`Entry`] to track the state of each file/directory, can look up absolute paths for entries.
  96pub enum Worktree {
  97    Local(LocalWorktree),
  98    Remote(RemoteWorktree),
  99}
 100
 101pub struct LocalWorktree {
 102    snapshot: LocalSnapshot,
 103    scan_requests_tx: channel::Sender<ScanRequest>,
 104    path_prefixes_to_scan_tx: channel::Sender<Arc<Path>>,
 105    is_scanning: (watch::Sender<bool>, watch::Receiver<bool>),
 106    _background_scanner_tasks: Vec<Task<()>>,
 107    share: Option<ShareState>,
 108    diagnostics: HashMap<
 109        Arc<Path>,
 110        Vec<(
 111            LanguageServerId,
 112            Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 113        )>,
 114    >,
 115    diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
 116    client: Arc<Client>,
 117    fs: Arc<dyn Fs>,
 118    fs_case_sensitive: bool,
 119    visible: bool,
 120
 121    next_entry_id: Arc<AtomicUsize>,
 122}
 123
 124struct ScanRequest {
 125    relative_paths: Vec<Arc<Path>>,
 126    done: barrier::Sender,
 127}
 128
 129pub struct RemoteWorktree {
 130    snapshot: Snapshot,
 131    background_snapshot: Arc<Mutex<Snapshot>>,
 132    project_id: u64,
 133    client: Arc<Client>,
 134    updates_tx: Option<UnboundedSender<proto::UpdateWorktree>>,
 135    snapshot_subscriptions: VecDeque<(usize, oneshot::Sender<()>)>,
 136    replica_id: ReplicaId,
 137    diagnostic_summaries: HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>,
 138    visible: bool,
 139    disconnected: bool,
 140}
 141
 142#[derive(Clone)]
 143pub struct Snapshot {
 144    id: WorktreeId,
 145    abs_path: Arc<Path>,
 146    root_name: String,
 147    root_char_bag: CharBag,
 148    entries_by_path: SumTree<Entry>,
 149    entries_by_id: SumTree<PathEntry>,
 150    repository_entries: TreeMap<RepositoryWorkDirectory, RepositoryEntry>,
 151
 152    /// A number that increases every time the worktree begins scanning
 153    /// a set of paths from the filesystem. This scanning could be caused
 154    /// by some operation performed on the worktree, such as reading or
 155    /// writing a file, or by an event reported by the filesystem.
 156    scan_id: usize,
 157
 158    /// The latest scan id that has completed, and whose preceding scans
 159    /// have all completed. The current `scan_id` could be more than one
 160    /// greater than the `completed_scan_id` if operations are performed
 161    /// on the worktree while it is processing a file-system event.
 162    completed_scan_id: usize,
 163}
 164
 165#[derive(Clone, Debug, PartialEq, Eq)]
 166pub struct RepositoryEntry {
 167    pub(crate) work_directory: WorkDirectoryEntry,
 168    pub(crate) branch: Option<Arc<str>>,
 169
 170    /// If location_in_repo is set, it means the .git folder is external
 171    /// and in a parent folder of the project root.
 172    /// In that case, the work_directory field will point to the
 173    /// project-root and location_in_repo contains the location of the
 174    /// project-root in the repository.
 175    ///
 176    /// Example:
 177    ///
 178    ///     my_root_folder/          <-- repository root
 179    ///       .git
 180    ///       my_sub_folder_1/
 181    ///         project_root/        <-- Project root, Zed opened here
 182    ///           ...
 183    ///
 184    /// For this setup, the attributes will have the following values:
 185    ///
 186    ///     work_directory: pointing to "" entry
 187    ///     location_in_repo: Some("my_sub_folder_1/project_root")
 188    pub(crate) location_in_repo: Option<Arc<Path>>,
 189}
 190
 191impl RepositoryEntry {
 192    pub fn branch(&self) -> Option<Arc<str>> {
 193        self.branch.clone()
 194    }
 195
 196    pub fn work_directory_id(&self) -> ProjectEntryId {
 197        *self.work_directory
 198    }
 199
 200    pub fn work_directory(&self, snapshot: &Snapshot) -> Option<RepositoryWorkDirectory> {
 201        snapshot
 202            .entry_for_id(self.work_directory_id())
 203            .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
 204    }
 205
 206    pub fn build_update(&self, _: &Self) -> proto::RepositoryEntry {
 207        self.into()
 208    }
 209
 210    /// relativize returns the given project path relative to the root folder of the
 211    /// repository.
 212    /// If the root of the repository (and its .git folder) are located in a parent folder
 213    /// of the project root folder, then the returned RepoPath is relative to the root
 214    /// of the repository and not a valid path inside the project.
 215    pub fn relativize(&self, worktree: &Snapshot, path: &Path) -> Result<RepoPath> {
 216        let relativize_path = |path: &Path| {
 217            let entry = worktree
 218                .entry_for_id(self.work_directory.0)
 219                .ok_or_else(|| anyhow!("entry not found"))?;
 220
 221            let relativized_path = path
 222                .strip_prefix(&entry.path)
 223                .map_err(|_| anyhow!("could not relativize {:?} against {:?}", path, entry.path))?;
 224
 225            Ok(relativized_path.into())
 226        };
 227
 228        if let Some(location_in_repo) = &self.location_in_repo {
 229            relativize_path(&location_in_repo.join(path))
 230        } else {
 231            relativize_path(path)
 232        }
 233    }
 234}
 235
 236impl From<&RepositoryEntry> for proto::RepositoryEntry {
 237    fn from(value: &RepositoryEntry) -> Self {
 238        proto::RepositoryEntry {
 239            work_directory_id: value.work_directory.to_proto(),
 240            branch: value.branch.as_ref().map(|str| str.to_string()),
 241        }
 242    }
 243}
 244
 245/// This path corresponds to the 'content path' of a repository in relation
 246/// to Zed's project root.
 247/// In the majority of the cases, this is the folder that contains the .git folder.
 248/// But if a sub-folder of a git repository is opened, this corresponds to the
 249/// project root and the .git folder is located in a parent directory.
 250#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
 251pub struct RepositoryWorkDirectory(pub(crate) Arc<Path>);
 252
 253impl Default for RepositoryWorkDirectory {
 254    fn default() -> Self {
 255        RepositoryWorkDirectory(Arc::from(Path::new("")))
 256    }
 257}
 258
 259impl AsRef<Path> for RepositoryWorkDirectory {
 260    fn as_ref(&self) -> &Path {
 261        self.0.as_ref()
 262    }
 263}
 264
 265#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq)]
 266pub struct WorkDirectoryEntry(ProjectEntryId);
 267
 268impl Deref for WorkDirectoryEntry {
 269    type Target = ProjectEntryId;
 270
 271    fn deref(&self) -> &Self::Target {
 272        &self.0
 273    }
 274}
 275
 276impl From<ProjectEntryId> for WorkDirectoryEntry {
 277    fn from(value: ProjectEntryId) -> Self {
 278        WorkDirectoryEntry(value)
 279    }
 280}
 281
 282#[derive(Debug, Clone)]
 283pub struct LocalSnapshot {
 284    snapshot: Snapshot,
 285    /// All of the gitignore files in the worktree, indexed by their relative path.
 286    /// The boolean indicates whether the gitignore needs to be updated.
 287    ignores_by_parent_abs_path: HashMap<Arc<Path>, (Arc<Gitignore>, bool)>,
 288    /// All of the git repositories in the worktree, indexed by the project entry
 289    /// id of their parent directory.
 290    git_repositories: TreeMap<ProjectEntryId, LocalRepositoryEntry>,
 291    file_scan_exclusions: Vec<PathMatcher>,
 292    private_files: Vec<PathMatcher>,
 293    share_private_files: bool,
 294}
 295
 296struct BackgroundScannerState {
 297    snapshot: LocalSnapshot,
 298    scanned_dirs: HashSet<ProjectEntryId>,
 299    path_prefixes_to_scan: HashSet<Arc<Path>>,
 300    paths_to_scan: HashSet<Arc<Path>>,
 301    /// The ids of all of the entries that were removed from the snapshot
 302    /// as part of the current update. These entry ids may be re-used
 303    /// if the same inode is discovered at a new path, or if the given
 304    /// path is re-created after being deleted.
 305    removed_entry_ids: HashMap<u64, ProjectEntryId>,
 306    changed_paths: Vec<Arc<Path>>,
 307    prev_snapshot: Snapshot,
 308}
 309
 310#[derive(Debug, Clone)]
 311pub struct LocalRepositoryEntry {
 312    pub(crate) git_dir_scan_id: usize,
 313    pub(crate) repo_ptr: Arc<Mutex<dyn GitRepository>>,
 314    /// Path to the actual .git folder.
 315    /// Note: if .git is a file, this points to the folder indicated by the .git file
 316    pub(crate) git_dir_path: Arc<Path>,
 317}
 318
 319impl LocalRepositoryEntry {
 320    pub fn repo(&self) -> &Arc<Mutex<dyn GitRepository>> {
 321        &self.repo_ptr
 322    }
 323}
 324
 325impl Deref for LocalSnapshot {
 326    type Target = Snapshot;
 327
 328    fn deref(&self) -> &Self::Target {
 329        &self.snapshot
 330    }
 331}
 332
 333impl DerefMut for LocalSnapshot {
 334    fn deref_mut(&mut self) -> &mut Self::Target {
 335        &mut self.snapshot
 336    }
 337}
 338
 339enum ScanState {
 340    Started,
 341    Updated {
 342        snapshot: LocalSnapshot,
 343        changes: UpdatedEntriesSet,
 344        barrier: Option<barrier::Sender>,
 345        scanning: bool,
 346    },
 347}
 348
 349struct ShareState {
 350    project_id: u64,
 351    snapshots_tx:
 352        mpsc::UnboundedSender<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>,
 353    resume_updates: watch::Sender<()>,
 354    _maintain_remote_snapshot: Task<Option<()>>,
 355}
 356
 357#[derive(Clone)]
 358pub enum Event {
 359    UpdatedEntries(UpdatedEntriesSet),
 360    UpdatedGitRepositories(UpdatedGitRepositoriesSet),
 361}
 362
 363impl EventEmitter<Event> for Worktree {}
 364
 365impl Worktree {
 366    pub async fn local(
 367        client: Arc<Client>,
 368        path: impl Into<Arc<Path>>,
 369        visible: bool,
 370        fs: Arc<dyn Fs>,
 371        next_entry_id: Arc<AtomicUsize>,
 372        cx: &mut AsyncAppContext,
 373    ) -> Result<Model<Self>> {
 374        // After determining whether the root entry is a file or a directory, populate the
 375        // snapshot's "root name", which will be used for the purpose of fuzzy matching.
 376        let abs_path = path.into();
 377
 378        let metadata = fs
 379            .metadata(&abs_path)
 380            .await
 381            .context("failed to stat worktree path")?;
 382
 383        let fs_case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
 384            log::error!(
 385                "Failed to determine whether filesystem is case sensitive (falling back to true) due to error: {e:#}"
 386            );
 387            true
 388        });
 389
 390        cx.new_model(move |cx: &mut ModelContext<Worktree>| {
 391            cx.observe_global::<SettingsStore>(move |this, cx| {
 392                if let Self::Local(this) = this {
 393                    let new_file_scan_exclusions = path_matchers(
 394                        WorktreeSettings::get_global(cx)
 395                            .file_scan_exclusions
 396                            .as_deref(),
 397                        "file_scan_exclusions",
 398                    );
 399                    let new_private_files = path_matchers(
 400                        WorktreeSettings::get(Some(settings::SettingsLocation {
 401                            worktree_id: cx.handle().entity_id().as_u64() as usize,
 402                            path: Path::new("")
 403                        }), cx).private_files.as_deref(),
 404                        "private_files",
 405                    );
 406
 407                    if new_file_scan_exclusions != this.snapshot.file_scan_exclusions
 408                        || new_private_files != this.snapshot.private_files
 409                    {
 410                        this.snapshot.file_scan_exclusions = new_file_scan_exclusions;
 411                        this.snapshot.private_files = new_private_files;
 412
 413                        log::info!(
 414                            "Re-scanning directories, new scan exclude files: {:?}, new dotenv files: {:?}",
 415                            this.snapshot
 416                                .file_scan_exclusions
 417                                .iter()
 418                                .map(ToString::to_string)
 419                                .collect::<Vec<_>>(),
 420                            this.snapshot
 421                                .private_files
 422                                .iter()
 423                                .map(ToString::to_string)
 424                                .collect::<Vec<_>>()
 425                        );
 426
 427                        this.restart_background_scanners(cx);
 428                    }
 429                }
 430            })
 431            .detach();
 432
 433            let root_name = abs_path
 434                .file_name()
 435                .map_or(String::new(), |f| f.to_string_lossy().to_string());
 436
 437            let mut snapshot = LocalSnapshot {
 438                file_scan_exclusions: path_matchers(
 439                    WorktreeSettings::get_global(cx)
 440                        .file_scan_exclusions
 441                        .as_deref(),
 442                    "file_scan_exclusions",
 443                ),
 444                private_files: path_matchers(
 445                    WorktreeSettings::get(Some(SettingsLocation {
 446                        worktree_id: cx.handle().entity_id().as_u64() as usize,
 447                        path: Path::new(""),
 448                    }), cx).private_files.as_deref(),
 449                    "private_files",
 450                ),
 451                share_private_files: false,
 452                ignores_by_parent_abs_path: Default::default(),
 453                git_repositories: Default::default(),
 454                snapshot: Snapshot {
 455                    id: WorktreeId::from_usize(cx.entity_id().as_u64() as usize),
 456                    abs_path: abs_path.to_path_buf().into(),
 457                    root_name: root_name.clone(),
 458                    root_char_bag: root_name.chars().map(|c| c.to_ascii_lowercase()).collect(),
 459                    entries_by_path: Default::default(),
 460                    entries_by_id: Default::default(),
 461                    repository_entries: Default::default(),
 462                    scan_id: 1,
 463                    completed_scan_id: 0,
 464                },
 465            };
 466
 467            if let Some(metadata) = metadata {
 468                snapshot.insert_entry(
 469                    Entry::new(
 470                        Arc::from(Path::new("")),
 471                        &metadata,
 472                        &next_entry_id,
 473                        snapshot.root_char_bag,
 474                        None
 475                    ),
 476                    fs.as_ref(),
 477                );
 478            }
 479
 480            let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
 481            let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
 482            let task_snapshot = snapshot.clone();
 483            Worktree::Local(LocalWorktree {
 484                next_entry_id: Arc::clone(&next_entry_id),
 485                snapshot,
 486                is_scanning: watch::channel_with(true),
 487                share: None,
 488                scan_requests_tx,
 489                path_prefixes_to_scan_tx,
 490                _background_scanner_tasks: start_background_scan_tasks(
 491                    &abs_path,
 492                    task_snapshot,
 493                    scan_requests_rx,
 494                    path_prefixes_to_scan_rx,
 495                    Arc::clone(&next_entry_id),
 496                    Arc::clone(&fs),
 497                    cx,
 498                ),
 499                diagnostics: Default::default(),
 500                diagnostic_summaries: Default::default(),
 501                client,
 502                fs,
 503                fs_case_sensitive,
 504                visible,
 505            })
 506        })
 507    }
 508
 509    pub fn remote(
 510        project_remote_id: u64,
 511        replica_id: ReplicaId,
 512        worktree: proto::WorktreeMetadata,
 513        client: Arc<Client>,
 514        cx: &mut AppContext,
 515    ) -> Model<Self> {
 516        cx.new_model(|cx: &mut ModelContext<Self>| {
 517            let snapshot = Snapshot {
 518                id: WorktreeId(worktree.id as usize),
 519                abs_path: Arc::from(PathBuf::from(worktree.abs_path)),
 520                root_name: worktree.root_name.clone(),
 521                root_char_bag: worktree
 522                    .root_name
 523                    .chars()
 524                    .map(|c| c.to_ascii_lowercase())
 525                    .collect(),
 526                entries_by_path: Default::default(),
 527                entries_by_id: Default::default(),
 528                repository_entries: Default::default(),
 529                scan_id: 1,
 530                completed_scan_id: 0,
 531            };
 532
 533            let (updates_tx, mut updates_rx) = mpsc::unbounded();
 534            let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
 535            let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
 536
 537            cx.background_executor()
 538                .spawn({
 539                    let background_snapshot = background_snapshot.clone();
 540                    async move {
 541                        while let Some(update) = updates_rx.next().await {
 542                            if let Err(error) =
 543                                background_snapshot.lock().apply_remote_update(update)
 544                            {
 545                                log::error!("error applying worktree update: {}", error);
 546                            }
 547                            snapshot_updated_tx.send(()).await.ok();
 548                        }
 549                    }
 550                })
 551                .detach();
 552
 553            cx.spawn(|this, mut cx| async move {
 554                while (snapshot_updated_rx.recv().await).is_some() {
 555                    this.update(&mut cx, |this, cx| {
 556                        let this = this.as_remote_mut().unwrap();
 557                        this.snapshot = this.background_snapshot.lock().clone();
 558                        cx.emit(Event::UpdatedEntries(Arc::from([])));
 559                        cx.notify();
 560                        while let Some((scan_id, _)) = this.snapshot_subscriptions.front() {
 561                            if this.observed_snapshot(*scan_id) {
 562                                let (_, tx) = this.snapshot_subscriptions.pop_front().unwrap();
 563                                let _ = tx.send(());
 564                            } else {
 565                                break;
 566                            }
 567                        }
 568                    })?;
 569                }
 570                anyhow::Ok(())
 571            })
 572            .detach();
 573
 574            Worktree::Remote(RemoteWorktree {
 575                project_id: project_remote_id,
 576                replica_id,
 577                snapshot: snapshot.clone(),
 578                background_snapshot,
 579                updates_tx: Some(updates_tx),
 580                snapshot_subscriptions: Default::default(),
 581                client: client.clone(),
 582                diagnostic_summaries: Default::default(),
 583                visible: worktree.visible,
 584                disconnected: false,
 585            })
 586        })
 587    }
 588
 589    pub fn as_local(&self) -> Option<&LocalWorktree> {
 590        if let Worktree::Local(worktree) = self {
 591            Some(worktree)
 592        } else {
 593            None
 594        }
 595    }
 596
 597    pub fn as_remote(&self) -> Option<&RemoteWorktree> {
 598        if let Worktree::Remote(worktree) = self {
 599            Some(worktree)
 600        } else {
 601            None
 602        }
 603    }
 604
 605    pub fn as_local_mut(&mut self) -> Option<&mut LocalWorktree> {
 606        if let Worktree::Local(worktree) = self {
 607            Some(worktree)
 608        } else {
 609            None
 610        }
 611    }
 612
 613    pub fn as_remote_mut(&mut self) -> Option<&mut RemoteWorktree> {
 614        if let Worktree::Remote(worktree) = self {
 615            Some(worktree)
 616        } else {
 617            None
 618        }
 619    }
 620
 621    pub fn is_local(&self) -> bool {
 622        matches!(self, Worktree::Local(_))
 623    }
 624
 625    pub fn is_remote(&self) -> bool {
 626        !self.is_local()
 627    }
 628
 629    pub fn snapshot(&self) -> Snapshot {
 630        match self {
 631            Worktree::Local(worktree) => worktree.snapshot().snapshot,
 632            Worktree::Remote(worktree) => worktree.snapshot(),
 633        }
 634    }
 635
 636    pub fn scan_id(&self) -> usize {
 637        match self {
 638            Worktree::Local(worktree) => worktree.snapshot.scan_id,
 639            Worktree::Remote(worktree) => worktree.snapshot.scan_id,
 640        }
 641    }
 642
 643    pub fn completed_scan_id(&self) -> usize {
 644        match self {
 645            Worktree::Local(worktree) => worktree.snapshot.completed_scan_id,
 646            Worktree::Remote(worktree) => worktree.snapshot.completed_scan_id,
 647        }
 648    }
 649
 650    pub fn is_visible(&self) -> bool {
 651        match self {
 652            Worktree::Local(worktree) => worktree.visible,
 653            Worktree::Remote(worktree) => worktree.visible,
 654        }
 655    }
 656
 657    pub fn replica_id(&self) -> ReplicaId {
 658        match self {
 659            Worktree::Local(_) => 0,
 660            Worktree::Remote(worktree) => worktree.replica_id,
 661        }
 662    }
 663
 664    pub fn diagnostic_summaries(
 665        &self,
 666    ) -> impl Iterator<Item = (Arc<Path>, LanguageServerId, DiagnosticSummary)> + '_ {
 667        match self {
 668            Worktree::Local(worktree) => &worktree.diagnostic_summaries,
 669            Worktree::Remote(worktree) => &worktree.diagnostic_summaries,
 670        }
 671        .iter()
 672        .flat_map(|(path, summaries)| {
 673            summaries
 674                .iter()
 675                .map(move |(&server_id, &summary)| (path.clone(), server_id, summary))
 676        })
 677    }
 678
 679    pub fn abs_path(&self) -> Arc<Path> {
 680        match self {
 681            Worktree::Local(worktree) => worktree.abs_path.clone(),
 682            Worktree::Remote(worktree) => worktree.abs_path.clone(),
 683        }
 684    }
 685
 686    pub fn root_file(&self, cx: &mut ModelContext<Self>) -> Option<Arc<File>> {
 687        let entry = self.root_entry()?;
 688        Some(File::for_entry(entry.clone(), cx.handle()))
 689    }
 690}
 691
 692fn start_background_scan_tasks(
 693    abs_path: &Path,
 694    snapshot: LocalSnapshot,
 695    scan_requests_rx: channel::Receiver<ScanRequest>,
 696    path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
 697    next_entry_id: Arc<AtomicUsize>,
 698    fs: Arc<dyn Fs>,
 699    cx: &mut ModelContext<'_, Worktree>,
 700) -> Vec<Task<()>> {
 701    let (scan_states_tx, mut scan_states_rx) = mpsc::unbounded();
 702    let background_scanner = cx.background_executor().spawn({
 703        let abs_path = if cfg!(target_os = "windows") {
 704            abs_path.canonicalize().unwrap_or_else(|_| abs_path.to_path_buf())
 705        } else {
 706            abs_path.to_path_buf()
 707        };
 708        let background = cx.background_executor().clone();
 709        async move {
 710            let events = fs.watch(&abs_path, FS_WATCH_LATENCY).await;
 711            let case_sensitive = fs.is_case_sensitive().await.unwrap_or_else(|e| {
 712                log::error!(
 713                    "Failed to determine whether filesystem is case sensitive (falling back to true) due to error: {e:#}"
 714                );
 715                true
 716            });
 717
 718            BackgroundScanner::new(
 719                snapshot,
 720                next_entry_id,
 721                fs,
 722                case_sensitive,
 723                scan_states_tx,
 724                background,
 725                scan_requests_rx,
 726                path_prefixes_to_scan_rx,
 727            )
 728            .run(events)
 729            .await;
 730        }
 731    });
 732    let scan_state_updater = cx.spawn(|this, mut cx| async move {
 733        while let Some((state, this)) = scan_states_rx.next().await.zip(this.upgrade()) {
 734            this.update(&mut cx, |this, cx| {
 735                let this = this.as_local_mut().unwrap();
 736                match state {
 737                    ScanState::Started => {
 738                        *this.is_scanning.0.borrow_mut() = true;
 739                    }
 740                    ScanState::Updated {
 741                        snapshot,
 742                        changes,
 743                        barrier,
 744                        scanning,
 745                    } => {
 746                        *this.is_scanning.0.borrow_mut() = scanning;
 747                        this.set_snapshot(snapshot, changes, cx);
 748                        drop(barrier);
 749                    }
 750                }
 751                cx.notify();
 752            })
 753            .ok();
 754        }
 755    });
 756    vec![background_scanner, scan_state_updater]
 757}
 758
 759fn path_matchers(values: Option<&[String]>, context: &'static str) -> Vec<PathMatcher> {
 760    values
 761        .unwrap_or(&[])
 762        .iter()
 763        .sorted()
 764        .filter_map(|pattern| {
 765            PathMatcher::new(pattern)
 766                .map(Some)
 767                .unwrap_or_else(|e| {
 768                    log::error!(
 769                        "Skipping pattern {pattern} in `{}` project settings due to parsing error: {e:#}", context
 770                    );
 771                    None
 772                })
 773        })
 774        .collect()
 775}
 776
 777impl LocalWorktree {
 778    pub fn contains_abs_path(&self, path: &Path) -> bool {
 779        path.starts_with(&self.abs_path)
 780    }
 781
 782    pub fn load_buffer(
 783        &mut self,
 784        path: &Path,
 785        cx: &mut ModelContext<Worktree>,
 786    ) -> Task<Result<Model<Buffer>>> {
 787        let path = Arc::from(path);
 788        let reservation = cx.reserve_model();
 789        let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
 790        cx.spawn(move |this, mut cx| async move {
 791            let (file, contents, diff_base) = this
 792                .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))?
 793                .await?;
 794            let text_buffer = cx
 795                .background_executor()
 796                .spawn(async move { text::Buffer::new(0, buffer_id, contents) })
 797                .await;
 798            cx.insert_model(reservation, |_| {
 799                Buffer::build(
 800                    text_buffer,
 801                    diff_base,
 802                    Some(Arc::new(file)),
 803                    Capability::ReadWrite,
 804                )
 805            })
 806        })
 807    }
 808
 809    pub fn new_buffer(
 810        &mut self,
 811        path: Arc<Path>,
 812        cx: &mut ModelContext<Worktree>,
 813    ) -> Model<Buffer> {
 814        let worktree = cx.handle();
 815        cx.new_model(|cx| {
 816            let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 817            let text_buffer = text::Buffer::new(0, buffer_id, "".into());
 818            Buffer::build(
 819                text_buffer,
 820                None,
 821                Some(Arc::new(File {
 822                    worktree,
 823                    path,
 824                    mtime: None,
 825                    entry_id: None,
 826                    is_local: true,
 827                    is_deleted: false,
 828                    is_private: false,
 829                })),
 830                Capability::ReadWrite,
 831            )
 832        })
 833    }
 834
 835    pub fn diagnostics_for_path(
 836        &self,
 837        path: &Path,
 838    ) -> Vec<(
 839        LanguageServerId,
 840        Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 841    )> {
 842        self.diagnostics.get(path).cloned().unwrap_or_default()
 843    }
 844
 845    pub fn clear_diagnostics_for_language_server(
 846        &mut self,
 847        server_id: LanguageServerId,
 848        _: &mut ModelContext<Worktree>,
 849    ) {
 850        let worktree_id = self.id().to_proto();
 851        self.diagnostic_summaries
 852            .retain(|path, summaries_by_server_id| {
 853                if summaries_by_server_id.remove(&server_id).is_some() {
 854                    if let Some(share) = self.share.as_ref() {
 855                        self.client
 856                            .send(proto::UpdateDiagnosticSummary {
 857                                project_id: share.project_id,
 858                                worktree_id,
 859                                summary: Some(proto::DiagnosticSummary {
 860                                    path: path.to_string_lossy().to_string(),
 861                                    language_server_id: server_id.0 as u64,
 862                                    error_count: 0,
 863                                    warning_count: 0,
 864                                }),
 865                            })
 866                            .log_err();
 867                    }
 868                    !summaries_by_server_id.is_empty()
 869                } else {
 870                    true
 871                }
 872            });
 873
 874        self.diagnostics.retain(|_, diagnostics_by_server_id| {
 875            if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 876                diagnostics_by_server_id.remove(ix);
 877                !diagnostics_by_server_id.is_empty()
 878            } else {
 879                true
 880            }
 881        });
 882    }
 883
 884    pub fn update_diagnostics(
 885        &mut self,
 886        server_id: LanguageServerId,
 887        worktree_path: Arc<Path>,
 888        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 889        _: &mut ModelContext<Worktree>,
 890    ) -> Result<bool> {
 891        let summaries_by_server_id = self
 892            .diagnostic_summaries
 893            .entry(worktree_path.clone())
 894            .or_default();
 895
 896        let old_summary = summaries_by_server_id
 897            .remove(&server_id)
 898            .unwrap_or_default();
 899
 900        let new_summary = DiagnosticSummary::new(&diagnostics);
 901        if new_summary.is_empty() {
 902            if let Some(diagnostics_by_server_id) = self.diagnostics.get_mut(&worktree_path) {
 903                if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 904                    diagnostics_by_server_id.remove(ix);
 905                }
 906                if diagnostics_by_server_id.is_empty() {
 907                    self.diagnostics.remove(&worktree_path);
 908                }
 909            }
 910        } else {
 911            summaries_by_server_id.insert(server_id, new_summary);
 912            let diagnostics_by_server_id =
 913                self.diagnostics.entry(worktree_path.clone()).or_default();
 914            match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 915                Ok(ix) => {
 916                    diagnostics_by_server_id[ix] = (server_id, diagnostics);
 917                }
 918                Err(ix) => {
 919                    diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
 920                }
 921            }
 922        }
 923
 924        if !old_summary.is_empty() || !new_summary.is_empty() {
 925            if let Some(share) = self.share.as_ref() {
 926                self.client
 927                    .send(proto::UpdateDiagnosticSummary {
 928                        project_id: share.project_id,
 929                        worktree_id: self.id().to_proto(),
 930                        summary: Some(proto::DiagnosticSummary {
 931                            path: worktree_path.to_string_lossy().to_string(),
 932                            language_server_id: server_id.0 as u64,
 933                            error_count: new_summary.error_count as u32,
 934                            warning_count: new_summary.warning_count as u32,
 935                        }),
 936                    })
 937                    .log_err();
 938            }
 939        }
 940
 941        Ok(!old_summary.is_empty() || !new_summary.is_empty())
 942    }
 943
 944    fn restart_background_scanners(&mut self, cx: &mut ModelContext<Worktree>) {
 945        let (scan_requests_tx, scan_requests_rx) = channel::unbounded();
 946        let (path_prefixes_to_scan_tx, path_prefixes_to_scan_rx) = channel::unbounded();
 947        self.scan_requests_tx = scan_requests_tx;
 948        self.path_prefixes_to_scan_tx = path_prefixes_to_scan_tx;
 949        self._background_scanner_tasks = start_background_scan_tasks(
 950            &self.snapshot.abs_path,
 951            self.snapshot(),
 952            scan_requests_rx,
 953            path_prefixes_to_scan_rx,
 954            Arc::clone(&self.next_entry_id),
 955            Arc::clone(&self.fs),
 956            cx,
 957        );
 958        self.is_scanning = watch::channel_with(true);
 959    }
 960
 961    fn set_snapshot(
 962        &mut self,
 963        mut new_snapshot: LocalSnapshot,
 964        entry_changes: UpdatedEntriesSet,
 965        cx: &mut ModelContext<Worktree>,
 966    ) {
 967        let repo_changes = self.changed_repos(&self.snapshot, &new_snapshot);
 968
 969        new_snapshot.share_private_files = self.snapshot.share_private_files;
 970        self.snapshot = new_snapshot;
 971
 972        if let Some(share) = self.share.as_mut() {
 973            share
 974                .snapshots_tx
 975                .unbounded_send((
 976                    self.snapshot.clone(),
 977                    entry_changes.clone(),
 978                    repo_changes.clone(),
 979                ))
 980                .ok();
 981        }
 982
 983        if !entry_changes.is_empty() {
 984            cx.emit(Event::UpdatedEntries(entry_changes));
 985        }
 986        if !repo_changes.is_empty() {
 987            cx.emit(Event::UpdatedGitRepositories(repo_changes));
 988        }
 989    }
 990
 991    fn changed_repos(
 992        &self,
 993        old_snapshot: &LocalSnapshot,
 994        new_snapshot: &LocalSnapshot,
 995    ) -> UpdatedGitRepositoriesSet {
 996        let mut changes = Vec::new();
 997        let mut old_repos = old_snapshot.git_repositories.iter().peekable();
 998        let mut new_repos = new_snapshot.git_repositories.iter().peekable();
 999        loop {
1000            match (new_repos.peek().map(clone), old_repos.peek().map(clone)) {
1001                (Some((new_entry_id, new_repo)), Some((old_entry_id, old_repo))) => {
1002                    match Ord::cmp(&new_entry_id, &old_entry_id) {
1003                        Ordering::Less => {
1004                            if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
1005                                changes.push((
1006                                    entry.path.clone(),
1007                                    GitRepositoryChange {
1008                                        old_repository: None,
1009                                    },
1010                                ));
1011                            }
1012                            new_repos.next();
1013                        }
1014                        Ordering::Equal => {
1015                            if new_repo.git_dir_scan_id != old_repo.git_dir_scan_id {
1016                                if let Some(entry) = new_snapshot.entry_for_id(new_entry_id) {
1017                                    let old_repo = old_snapshot
1018                                        .repository_entries
1019                                        .get(&RepositoryWorkDirectory(entry.path.clone()))
1020                                        .cloned();
1021                                    changes.push((
1022                                        entry.path.clone(),
1023                                        GitRepositoryChange {
1024                                            old_repository: old_repo,
1025                                        },
1026                                    ));
1027                                }
1028                            }
1029                            new_repos.next();
1030                            old_repos.next();
1031                        }
1032                        Ordering::Greater => {
1033                            if let Some(entry) = old_snapshot.entry_for_id(old_entry_id) {
1034                                let old_repo = old_snapshot
1035                                    .repository_entries
1036                                    .get(&RepositoryWorkDirectory(entry.path.clone()))
1037                                    .cloned();
1038                                changes.push((
1039                                    entry.path.clone(),
1040                                    GitRepositoryChange {
1041                                        old_repository: old_repo,
1042                                    },
1043                                ));
1044                            }
1045                            old_repos.next();
1046                        }
1047                    }
1048                }
1049                (Some((entry_id, _)), None) => {
1050                    if let Some(entry) = new_snapshot.entry_for_id(entry_id) {
1051                        changes.push((
1052                            entry.path.clone(),
1053                            GitRepositoryChange {
1054                                old_repository: None,
1055                            },
1056                        ));
1057                    }
1058                    new_repos.next();
1059                }
1060                (None, Some((entry_id, _))) => {
1061                    if let Some(entry) = old_snapshot.entry_for_id(entry_id) {
1062                        let old_repo = old_snapshot
1063                            .repository_entries
1064                            .get(&RepositoryWorkDirectory(entry.path.clone()))
1065                            .cloned();
1066                        changes.push((
1067                            entry.path.clone(),
1068                            GitRepositoryChange {
1069                                old_repository: old_repo,
1070                            },
1071                        ));
1072                    }
1073                    old_repos.next();
1074                }
1075                (None, None) => break,
1076            }
1077        }
1078
1079        fn clone<T: Clone, U: Clone>(value: &(&T, &U)) -> (T, U) {
1080            (value.0.clone(), value.1.clone())
1081        }
1082
1083        changes.into()
1084    }
1085
1086    pub fn scan_complete(&self) -> impl Future<Output = ()> {
1087        let mut is_scanning_rx = self.is_scanning.1.clone();
1088        async move {
1089            let mut is_scanning = *is_scanning_rx.borrow();
1090            while is_scanning {
1091                if let Some(value) = is_scanning_rx.recv().await {
1092                    is_scanning = value;
1093                } else {
1094                    break;
1095                }
1096            }
1097        }
1098    }
1099
1100    pub fn snapshot(&self) -> LocalSnapshot {
1101        self.snapshot.clone()
1102    }
1103
1104    pub fn metadata_proto(&self) -> proto::WorktreeMetadata {
1105        proto::WorktreeMetadata {
1106            id: self.id().to_proto(),
1107            root_name: self.root_name().to_string(),
1108            visible: self.visible,
1109            abs_path: self.abs_path().as_os_str().to_string_lossy().into(),
1110        }
1111    }
1112
1113    fn load(
1114        &self,
1115        path: &Path,
1116        cx: &mut ModelContext<Worktree>,
1117    ) -> Task<Result<(File, String, Option<String>)>> {
1118        let path = Arc::from(path);
1119        let abs_path = self.absolutize(&path);
1120        let fs = self.fs.clone();
1121        let entry = self.refresh_entry(path.clone(), None, cx);
1122
1123        cx.spawn(|this, mut cx| async move {
1124            let abs_path = abs_path?;
1125            let text = fs.load(&abs_path).await?;
1126            let mut index_task = None;
1127            let snapshot = this.update(&mut cx, |this, _| this.as_local().unwrap().snapshot())?;
1128            if let Some(repo) = snapshot.repository_for_path(&path) {
1129                if let Some(repo_path) = repo.relativize(&snapshot, &path).log_err() {
1130                    if let Some(git_repo) = snapshot.git_repositories.get(&*repo.work_directory) {
1131                        let git_repo = git_repo.repo_ptr.clone();
1132                        index_task = Some(cx.background_executor().spawn({
1133                            let fs = fs.clone();
1134                            let abs_path = abs_path.clone();
1135                            async move {
1136                                let abs_path_metadata = fs
1137                                    .metadata(&abs_path)
1138                                    .await
1139                                    .with_context(|| {
1140                                        format!("loading file and FS metadata for {abs_path:?}")
1141                                    })
1142                                    .log_err()
1143                                    .flatten()?;
1144                                if abs_path_metadata.is_dir || abs_path_metadata.is_symlink {
1145                                    None
1146                                } else {
1147                                    git_repo.lock().load_index_text(&repo_path)
1148                                }
1149                            }
1150                        }));
1151                    }
1152                }
1153            }
1154
1155            let diff_base = if let Some(index_task) = index_task {
1156                index_task.await
1157            } else {
1158                None
1159            };
1160
1161            let worktree = this
1162                .upgrade()
1163                .ok_or_else(|| anyhow!("worktree was dropped"))?;
1164            match entry.await? {
1165                Some(entry) => Ok((
1166                    File {
1167                        entry_id: Some(entry.id),
1168                        worktree,
1169                        path: entry.path,
1170                        mtime: entry.mtime,
1171                        is_local: true,
1172                        is_deleted: false,
1173                        is_private: entry.is_private,
1174                    },
1175                    text,
1176                    diff_base,
1177                )),
1178                None => {
1179                    let metadata = fs
1180                        .metadata(&abs_path)
1181                        .await
1182                        .with_context(|| {
1183                            format!("Loading metadata for excluded file {abs_path:?}")
1184                        })?
1185                        .with_context(|| {
1186                            format!("Excluded file {abs_path:?} got removed during loading")
1187                        })?;
1188                    let is_private = snapshot.is_path_private(path.as_ref());
1189                    Ok((
1190                        File {
1191                            entry_id: None,
1192                            worktree,
1193                            path,
1194                            mtime: Some(metadata.mtime),
1195                            is_local: true,
1196                            is_deleted: false,
1197                            is_private,
1198                        },
1199                        text,
1200                        diff_base,
1201                    ))
1202                }
1203            }
1204        })
1205    }
1206
1207    pub fn save_buffer(
1208        &self,
1209        buffer_handle: Model<Buffer>,
1210        path: Arc<Path>,
1211        mut has_changed_file: bool,
1212        cx: &mut ModelContext<Worktree>,
1213    ) -> Task<Result<()>> {
1214        let buffer = buffer_handle.read(cx);
1215
1216        let rpc = self.client.clone();
1217        let buffer_id: u64 = buffer.remote_id().into();
1218        let project_id = self.share.as_ref().map(|share| share.project_id);
1219
1220        if buffer.file().is_some_and(|file| !file.is_created()) {
1221            has_changed_file = true;
1222        }
1223
1224        let text = buffer.as_rope().clone();
1225        let version = buffer.version();
1226        let save = self.write_file(path.as_ref(), text, buffer.line_ending(), cx);
1227        let fs = Arc::clone(&self.fs);
1228        let abs_path = self.absolutize(&path);
1229        let is_private = self.snapshot.is_path_private(&path);
1230
1231        cx.spawn(move |this, mut cx| async move {
1232            let entry = save.await?;
1233            let abs_path = abs_path?;
1234            let this = this.upgrade().context("worktree dropped")?;
1235
1236            let (entry_id, mtime, path, is_dotenv) = match entry {
1237                Some(entry) => (Some(entry.id), entry.mtime, entry.path, entry.is_private),
1238                None => {
1239                    let metadata = fs
1240                        .metadata(&abs_path)
1241                        .await
1242                        .with_context(|| {
1243                            format!(
1244                                "Fetching metadata after saving the excluded buffer {abs_path:?}"
1245                            )
1246                        })?
1247                        .with_context(|| {
1248                            format!("Excluded buffer {path:?} got removed during saving")
1249                        })?;
1250                    (None, Some(metadata.mtime), path, is_private)
1251                }
1252            };
1253
1254            if has_changed_file {
1255                let new_file = Arc::new(File {
1256                    entry_id,
1257                    worktree: this,
1258                    path,
1259                    mtime,
1260                    is_local: true,
1261                    is_deleted: false,
1262                    is_private: is_dotenv,
1263                });
1264
1265                if let Some(project_id) = project_id {
1266                    rpc.send(proto::UpdateBufferFile {
1267                        project_id,
1268                        buffer_id,
1269                        file: Some(new_file.to_proto()),
1270                    })
1271                    .log_err();
1272                }
1273
1274                buffer_handle.update(&mut cx, |buffer, cx| {
1275                    if has_changed_file {
1276                        buffer.file_updated(new_file, cx);
1277                    }
1278                })?;
1279            }
1280
1281            if let Some(project_id) = project_id {
1282                rpc.send(proto::BufferSaved {
1283                    project_id,
1284                    buffer_id,
1285                    version: serialize_version(&version),
1286                    mtime: mtime.map(|time| time.into()),
1287                })?;
1288            }
1289
1290            buffer_handle.update(&mut cx, |buffer, cx| {
1291                buffer.did_save(version.clone(), mtime, cx);
1292            })?;
1293
1294            Ok(())
1295        })
1296    }
1297
1298    /// Find the lowest path in the worktree's datastructures that is an ancestor
1299    fn lowest_ancestor(&self, path: &Path) -> PathBuf {
1300        let mut lowest_ancestor = None;
1301        for path in path.ancestors() {
1302            if self.entry_for_path(path).is_some() {
1303                lowest_ancestor = Some(path.to_path_buf());
1304                break;
1305            }
1306        }
1307
1308        lowest_ancestor.unwrap_or_else(|| PathBuf::from(""))
1309    }
1310
1311    pub fn create_entry(
1312        &self,
1313        path: impl Into<Arc<Path>>,
1314        is_dir: bool,
1315        cx: &mut ModelContext<Worktree>,
1316    ) -> Task<Result<Option<Entry>>> {
1317        let path = path.into();
1318        let lowest_ancestor = self.lowest_ancestor(&path);
1319        let abs_path = self.absolutize(&path);
1320        let fs = self.fs.clone();
1321        let write = cx.background_executor().spawn(async move {
1322            if is_dir {
1323                fs.create_dir(&abs_path?).await
1324            } else {
1325                fs.save(&abs_path?, &Default::default(), Default::default())
1326                    .await
1327            }
1328        });
1329
1330        cx.spawn(|this, mut cx| async move {
1331            write.await?;
1332            let (result, refreshes) = this.update(&mut cx, |this, cx| {
1333                let mut refreshes = Vec::new();
1334                let refresh_paths = path.strip_prefix(&lowest_ancestor).unwrap();
1335                for refresh_path in refresh_paths.ancestors() {
1336                    if refresh_path == Path::new("") {
1337                        continue;
1338                    }
1339                    let refresh_full_path = lowest_ancestor.join(refresh_path);
1340
1341                    refreshes.push(this.as_local_mut().unwrap().refresh_entry(
1342                        refresh_full_path.into(),
1343                        None,
1344                        cx,
1345                    ));
1346                }
1347                (
1348                    this.as_local_mut().unwrap().refresh_entry(path, None, cx),
1349                    refreshes,
1350                )
1351            })?;
1352            for refresh in refreshes {
1353                refresh.await.log_err();
1354            }
1355
1356            result.await
1357        })
1358    }
1359
1360    pub(crate) fn write_file(
1361        &self,
1362        path: impl Into<Arc<Path>>,
1363        text: Rope,
1364        line_ending: LineEnding,
1365        cx: &mut ModelContext<Worktree>,
1366    ) -> Task<Result<Option<Entry>>> {
1367        let path: Arc<Path> = path.into();
1368        let abs_path = self.absolutize(&path);
1369        let fs = self.fs.clone();
1370        let write = cx
1371            .background_executor()
1372            .spawn(async move { fs.save(&abs_path?, &text, line_ending).await });
1373
1374        cx.spawn(|this, mut cx| async move {
1375            write.await?;
1376            this.update(&mut cx, |this, cx| {
1377                this.as_local_mut().unwrap().refresh_entry(path, None, cx)
1378            })?
1379            .await
1380        })
1381    }
1382
1383    pub fn delete_entry(
1384        &self,
1385        entry_id: ProjectEntryId,
1386        trash: bool,
1387        cx: &mut ModelContext<Worktree>,
1388    ) -> Option<Task<Result<()>>> {
1389        let entry = self.entry_for_id(entry_id)?.clone();
1390        let abs_path = self.absolutize(&entry.path);
1391        let fs = self.fs.clone();
1392
1393        let delete = cx.background_executor().spawn(async move {
1394            if entry.is_file() {
1395                if trash {
1396                    fs.trash_file(&abs_path?, Default::default()).await?;
1397                } else {
1398                    fs.remove_file(&abs_path?, Default::default()).await?;
1399                }
1400            } else {
1401                if trash {
1402                    fs.trash_dir(
1403                        &abs_path?,
1404                        RemoveOptions {
1405                            recursive: true,
1406                            ignore_if_not_exists: false,
1407                        },
1408                    )
1409                    .await?;
1410                } else {
1411                    fs.remove_dir(
1412                        &abs_path?,
1413                        RemoveOptions {
1414                            recursive: true,
1415                            ignore_if_not_exists: false,
1416                        },
1417                    )
1418                    .await?;
1419                }
1420            }
1421            anyhow::Ok(entry.path)
1422        });
1423
1424        Some(cx.spawn(|this, mut cx| async move {
1425            let path = delete.await?;
1426            this.update(&mut cx, |this, _| {
1427                this.as_local_mut()
1428                    .unwrap()
1429                    .refresh_entries_for_paths(vec![path])
1430            })?
1431            .recv()
1432            .await;
1433            Ok(())
1434        }))
1435    }
1436
1437    pub fn rename_entry(
1438        &self,
1439        entry_id: ProjectEntryId,
1440        new_path: impl Into<Arc<Path>>,
1441        cx: &mut ModelContext<Worktree>,
1442    ) -> Task<Result<Option<Entry>>> {
1443        let old_path = match self.entry_for_id(entry_id) {
1444            Some(entry) => entry.path.clone(),
1445            None => return Task::ready(Ok(None)),
1446        };
1447        let new_path = new_path.into();
1448        let abs_old_path = self.absolutize(&old_path);
1449        let abs_new_path = self.absolutize(&new_path);
1450        let fs = self.fs.clone();
1451        let case_sensitive = self.fs_case_sensitive;
1452        let rename = cx.background_executor().spawn(async move {
1453            let abs_old_path = abs_old_path?;
1454            let abs_new_path = abs_new_path?;
1455
1456            let abs_old_path_lower = abs_old_path.to_str().map(|p| p.to_lowercase());
1457            let abs_new_path_lower = abs_new_path.to_str().map(|p| p.to_lowercase());
1458
1459            // If we're on a case-insensitive FS and we're doing a case-only rename (i.e. `foobar` to `FOOBAR`)
1460            // we want to overwrite, because otherwise we run into a file-already-exists error.
1461            let overwrite = !case_sensitive
1462                && abs_old_path != abs_new_path
1463                && abs_old_path_lower == abs_new_path_lower;
1464
1465            fs.rename(
1466                &abs_old_path,
1467                &abs_new_path,
1468                fs::RenameOptions {
1469                    overwrite,
1470                    ..Default::default()
1471                },
1472            )
1473            .await
1474        });
1475
1476        cx.spawn(|this, mut cx| async move {
1477            rename.await?;
1478            this.update(&mut cx, |this, cx| {
1479                this.as_local_mut()
1480                    .unwrap()
1481                    .refresh_entry(new_path.clone(), Some(old_path), cx)
1482            })?
1483            .await
1484        })
1485    }
1486
1487    pub fn copy_entry(
1488        &self,
1489        entry_id: ProjectEntryId,
1490        new_path: impl Into<Arc<Path>>,
1491        cx: &mut ModelContext<Worktree>,
1492    ) -> Task<Result<Option<Entry>>> {
1493        let old_path = match self.entry_for_id(entry_id) {
1494            Some(entry) => entry.path.clone(),
1495            None => return Task::ready(Ok(None)),
1496        };
1497        let new_path = new_path.into();
1498        let abs_old_path = self.absolutize(&old_path);
1499        let abs_new_path = self.absolutize(&new_path);
1500        let fs = self.fs.clone();
1501        let copy = cx.background_executor().spawn(async move {
1502            copy_recursive(
1503                fs.as_ref(),
1504                &abs_old_path?,
1505                &abs_new_path?,
1506                Default::default(),
1507            )
1508            .await
1509        });
1510
1511        cx.spawn(|this, mut cx| async move {
1512            copy.await?;
1513            this.update(&mut cx, |this, cx| {
1514                this.as_local_mut()
1515                    .unwrap()
1516                    .refresh_entry(new_path.clone(), None, cx)
1517            })?
1518            .await
1519        })
1520    }
1521
1522    pub fn expand_entry(
1523        &mut self,
1524        entry_id: ProjectEntryId,
1525        cx: &mut ModelContext<Worktree>,
1526    ) -> Option<Task<Result<()>>> {
1527        let path = self.entry_for_id(entry_id)?.path.clone();
1528        let mut refresh = self.refresh_entries_for_paths(vec![path]);
1529        Some(cx.background_executor().spawn(async move {
1530            refresh.next().await;
1531            Ok(())
1532        }))
1533    }
1534
1535    pub fn refresh_entries_for_paths(&self, paths: Vec<Arc<Path>>) -> barrier::Receiver {
1536        let (tx, rx) = barrier::channel();
1537        self.scan_requests_tx
1538            .try_send(ScanRequest {
1539                relative_paths: paths,
1540                done: tx,
1541            })
1542            .ok();
1543        rx
1544    }
1545
1546    pub fn add_path_prefix_to_scan(&self, path_prefix: Arc<Path>) {
1547        self.path_prefixes_to_scan_tx.try_send(path_prefix).ok();
1548    }
1549
1550    fn refresh_entry(
1551        &self,
1552        path: Arc<Path>,
1553        old_path: Option<Arc<Path>>,
1554        cx: &mut ModelContext<Worktree>,
1555    ) -> Task<Result<Option<Entry>>> {
1556        if self.is_path_excluded(&path) {
1557            return Task::ready(Ok(None));
1558        }
1559        let paths = if let Some(old_path) = old_path.as_ref() {
1560            vec![old_path.clone(), path.clone()]
1561        } else {
1562            vec![path.clone()]
1563        };
1564        let t0 = Instant::now();
1565        let mut refresh = self.refresh_entries_for_paths(paths);
1566        cx.spawn(move |this, mut cx| async move {
1567            refresh.recv().await;
1568            log::trace!("refreshed entry {path:?} in {:?}", t0.elapsed());
1569            let new_entry = this.update(&mut cx, |this, _| {
1570                this.entry_for_path(path)
1571                    .cloned()
1572                    .ok_or_else(|| anyhow!("failed to read path after update"))
1573            })??;
1574            Ok(Some(new_entry))
1575        })
1576    }
1577
1578    pub fn observe_updates<F, Fut>(
1579        &mut self,
1580        project_id: u64,
1581        cx: &mut ModelContext<Worktree>,
1582        callback: F,
1583    ) -> oneshot::Receiver<()>
1584    where
1585        F: 'static + Send + Fn(proto::UpdateWorktree) -> Fut,
1586        Fut: Send + Future<Output = bool>,
1587    {
1588        #[cfg(any(test, feature = "test-support"))]
1589        const MAX_CHUNK_SIZE: usize = 2;
1590        #[cfg(not(any(test, feature = "test-support")))]
1591        const MAX_CHUNK_SIZE: usize = 256;
1592
1593        let (share_tx, share_rx) = oneshot::channel();
1594
1595        if let Some(share) = self.share.as_mut() {
1596            share_tx.send(()).ok();
1597            *share.resume_updates.borrow_mut() = ();
1598            return share_rx;
1599        }
1600
1601        let (resume_updates_tx, mut resume_updates_rx) = watch::channel::<()>();
1602        let (snapshots_tx, mut snapshots_rx) =
1603            mpsc::unbounded::<(LocalSnapshot, UpdatedEntriesSet, UpdatedGitRepositoriesSet)>();
1604        snapshots_tx
1605            .unbounded_send((self.snapshot(), Arc::from([]), Arc::from([])))
1606            .ok();
1607
1608        let worktree_id = cx.entity_id().as_u64();
1609        let _maintain_remote_snapshot = cx.background_executor().spawn(async move {
1610            let mut is_first = true;
1611            while let Some((snapshot, entry_changes, repo_changes)) = snapshots_rx.next().await {
1612                let update;
1613                if is_first {
1614                    update = snapshot.build_initial_update(project_id, worktree_id);
1615                    is_first = false;
1616                } else {
1617                    update =
1618                        snapshot.build_update(project_id, worktree_id, entry_changes, repo_changes);
1619                }
1620
1621                for update in proto::split_worktree_update(update, MAX_CHUNK_SIZE) {
1622                    let _ = resume_updates_rx.try_recv();
1623                    loop {
1624                        let result = callback(update.clone());
1625                        if result.await {
1626                            break;
1627                        } else {
1628                            log::info!("waiting to resume updates");
1629                            if resume_updates_rx.next().await.is_none() {
1630                                return Some(());
1631                            }
1632                        }
1633                    }
1634                }
1635            }
1636            share_tx.send(()).ok();
1637            Some(())
1638        });
1639
1640        self.share = Some(ShareState {
1641            project_id,
1642            snapshots_tx,
1643            resume_updates: resume_updates_tx,
1644            _maintain_remote_snapshot,
1645        });
1646        share_rx
1647    }
1648
1649    pub fn share(&mut self, project_id: u64, cx: &mut ModelContext<Worktree>) -> Task<Result<()>> {
1650        let client = self.client.clone();
1651
1652        for (path, summaries) in &self.diagnostic_summaries {
1653            for (&server_id, summary) in summaries {
1654                if let Err(e) = self.client.send(proto::UpdateDiagnosticSummary {
1655                    project_id,
1656                    worktree_id: cx.entity_id().as_u64(),
1657                    summary: Some(summary.to_proto(server_id, path)),
1658                }) {
1659                    return Task::ready(Err(e));
1660                }
1661            }
1662        }
1663
1664        let rx = self.observe_updates(project_id, cx, move |update| {
1665            client.request(update).map(|result| result.is_ok())
1666        });
1667        cx.background_executor()
1668            .spawn(async move { rx.await.map_err(|_| anyhow!("share ended")) })
1669    }
1670
1671    pub fn unshare(&mut self) {
1672        self.share.take();
1673    }
1674
1675    pub fn is_shared(&self) -> bool {
1676        self.share.is_some()
1677    }
1678
1679    pub fn share_private_files(&mut self, cx: &mut ModelContext<Worktree>) {
1680        self.snapshot.share_private_files = true;
1681        self.restart_background_scanners(cx);
1682    }
1683}
1684
1685impl RemoteWorktree {
1686    fn snapshot(&self) -> Snapshot {
1687        self.snapshot.clone()
1688    }
1689
1690    pub fn disconnected_from_host(&mut self) {
1691        self.updates_tx.take();
1692        self.snapshot_subscriptions.clear();
1693        self.disconnected = true;
1694    }
1695
1696    pub fn save_buffer(
1697        &self,
1698        buffer_handle: Model<Buffer>,
1699        new_path: Option<proto::ProjectPath>,
1700        cx: &mut ModelContext<Worktree>,
1701    ) -> Task<Result<()>> {
1702        let buffer = buffer_handle.read(cx);
1703        let buffer_id = buffer.remote_id().into();
1704        let version = buffer.version();
1705        let rpc = self.client.clone();
1706        let project_id = self.project_id;
1707        cx.spawn(move |_, mut cx| async move {
1708            let response = rpc
1709                .request(proto::SaveBuffer {
1710                    project_id,
1711                    buffer_id,
1712                    new_path,
1713                    version: serialize_version(&version),
1714                })
1715                .await?;
1716            let version = deserialize_version(&response.version);
1717            let mtime = response.mtime.map(|mtime| mtime.into());
1718
1719            buffer_handle.update(&mut cx, |buffer, cx| {
1720                buffer.did_save(version.clone(), mtime, cx);
1721            })?;
1722
1723            Ok(())
1724        })
1725    }
1726
1727    pub fn update_from_remote(&mut self, update: proto::UpdateWorktree) {
1728        if let Some(updates_tx) = &self.updates_tx {
1729            updates_tx
1730                .unbounded_send(update)
1731                .expect("consumer runs to completion");
1732        }
1733    }
1734
1735    fn observed_snapshot(&self, scan_id: usize) -> bool {
1736        self.completed_scan_id >= scan_id
1737    }
1738
1739    pub fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
1740        let (tx, rx) = oneshot::channel();
1741        if self.observed_snapshot(scan_id) {
1742            let _ = tx.send(());
1743        } else if self.disconnected {
1744            drop(tx);
1745        } else {
1746            match self
1747                .snapshot_subscriptions
1748                .binary_search_by_key(&scan_id, |probe| probe.0)
1749            {
1750                Ok(ix) | Err(ix) => self.snapshot_subscriptions.insert(ix, (scan_id, tx)),
1751            }
1752        }
1753
1754        async move {
1755            rx.await?;
1756            Ok(())
1757        }
1758    }
1759
1760    pub fn update_diagnostic_summary(
1761        &mut self,
1762        path: Arc<Path>,
1763        summary: &proto::DiagnosticSummary,
1764    ) {
1765        let server_id = LanguageServerId(summary.language_server_id as usize);
1766        let summary = DiagnosticSummary {
1767            error_count: summary.error_count as usize,
1768            warning_count: summary.warning_count as usize,
1769        };
1770
1771        if summary.is_empty() {
1772            if let Some(summaries) = self.diagnostic_summaries.get_mut(&path) {
1773                summaries.remove(&server_id);
1774                if summaries.is_empty() {
1775                    self.diagnostic_summaries.remove(&path);
1776                }
1777            }
1778        } else {
1779            self.diagnostic_summaries
1780                .entry(path)
1781                .or_default()
1782                .insert(server_id, summary);
1783        }
1784    }
1785
1786    pub fn insert_entry(
1787        &mut self,
1788        entry: proto::Entry,
1789        scan_id: usize,
1790        cx: &mut ModelContext<Worktree>,
1791    ) -> Task<Result<Entry>> {
1792        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1793        cx.spawn(|this, mut cx| async move {
1794            wait_for_snapshot.await?;
1795            this.update(&mut cx, |worktree, _| {
1796                let worktree = worktree.as_remote_mut().unwrap();
1797                let mut snapshot = worktree.background_snapshot.lock();
1798                let entry = snapshot.insert_entry(entry);
1799                worktree.snapshot = snapshot.clone();
1800                entry
1801            })?
1802        })
1803    }
1804
1805    pub fn delete_entry(
1806        &mut self,
1807        id: ProjectEntryId,
1808        scan_id: usize,
1809        cx: &mut ModelContext<Worktree>,
1810    ) -> Task<Result<()>> {
1811        let wait_for_snapshot = self.wait_for_snapshot(scan_id);
1812        cx.spawn(move |this, mut cx| async move {
1813            wait_for_snapshot.await?;
1814            this.update(&mut cx, |worktree, _| {
1815                let worktree = worktree.as_remote_mut().unwrap();
1816                let mut snapshot = worktree.background_snapshot.lock();
1817                snapshot.delete_entry(id);
1818                worktree.snapshot = snapshot.clone();
1819            })?;
1820            Ok(())
1821        })
1822    }
1823}
1824
1825impl Snapshot {
1826    pub fn id(&self) -> WorktreeId {
1827        self.id
1828    }
1829
1830    pub fn abs_path(&self) -> &Arc<Path> {
1831        &self.abs_path
1832    }
1833
1834    pub fn absolutize(&self, path: &Path) -> Result<PathBuf> {
1835        if path
1836            .components()
1837            .any(|component| !matches!(component, std::path::Component::Normal(_)))
1838        {
1839            return Err(anyhow!("invalid path"));
1840        }
1841        if path.file_name().is_some() {
1842            Ok(self.abs_path.join(path))
1843        } else {
1844            Ok(self.abs_path.to_path_buf())
1845        }
1846    }
1847
1848    pub fn contains_entry(&self, entry_id: ProjectEntryId) -> bool {
1849        self.entries_by_id.get(&entry_id, &()).is_some()
1850    }
1851
1852    fn insert_entry(&mut self, entry: proto::Entry) -> Result<Entry> {
1853        let entry = Entry::try_from((&self.root_char_bag, entry))?;
1854        let old_entry = self.entries_by_id.insert_or_replace(
1855            PathEntry {
1856                id: entry.id,
1857                path: entry.path.clone(),
1858                is_ignored: entry.is_ignored,
1859                scan_id: 0,
1860            },
1861            &(),
1862        );
1863        if let Some(old_entry) = old_entry {
1864            self.entries_by_path.remove(&PathKey(old_entry.path), &());
1865        }
1866        self.entries_by_path.insert_or_replace(entry.clone(), &());
1867        Ok(entry)
1868    }
1869
1870    fn delete_entry(&mut self, entry_id: ProjectEntryId) -> Option<Arc<Path>> {
1871        let removed_entry = self.entries_by_id.remove(&entry_id, &())?;
1872        self.entries_by_path = {
1873            let mut cursor = self.entries_by_path.cursor::<TraversalProgress>();
1874            let mut new_entries_by_path =
1875                cursor.slice(&TraversalTarget::Path(&removed_entry.path), Bias::Left, &());
1876            while let Some(entry) = cursor.item() {
1877                if entry.path.starts_with(&removed_entry.path) {
1878                    self.entries_by_id.remove(&entry.id, &());
1879                    cursor.next(&());
1880                } else {
1881                    break;
1882                }
1883            }
1884            new_entries_by_path.append(cursor.suffix(&()), &());
1885            new_entries_by_path
1886        };
1887
1888        Some(removed_entry.path)
1889    }
1890
1891    #[cfg(any(test, feature = "test-support"))]
1892    pub fn status_for_file(&self, path: impl Into<PathBuf>) -> Option<GitFileStatus> {
1893        let path = path.into();
1894        self.entries_by_path
1895            .get(&PathKey(Arc::from(path)), &())
1896            .and_then(|entry| entry.git_status)
1897    }
1898
1899    pub(crate) fn apply_remote_update(&mut self, mut update: proto::UpdateWorktree) -> Result<()> {
1900        let mut entries_by_path_edits = Vec::new();
1901        let mut entries_by_id_edits = Vec::new();
1902
1903        for entry_id in update.removed_entries {
1904            let entry_id = ProjectEntryId::from_proto(entry_id);
1905            entries_by_id_edits.push(Edit::Remove(entry_id));
1906            if let Some(entry) = self.entry_for_id(entry_id) {
1907                entries_by_path_edits.push(Edit::Remove(PathKey(entry.path.clone())));
1908            }
1909        }
1910
1911        for entry in update.updated_entries {
1912            let entry = Entry::try_from((&self.root_char_bag, entry))?;
1913            if let Some(PathEntry { path, .. }) = self.entries_by_id.get(&entry.id, &()) {
1914                entries_by_path_edits.push(Edit::Remove(PathKey(path.clone())));
1915            }
1916            if let Some(old_entry) = self.entries_by_path.get(&PathKey(entry.path.clone()), &()) {
1917                if old_entry.id != entry.id {
1918                    entries_by_id_edits.push(Edit::Remove(old_entry.id));
1919                }
1920            }
1921            entries_by_id_edits.push(Edit::Insert(PathEntry {
1922                id: entry.id,
1923                path: entry.path.clone(),
1924                is_ignored: entry.is_ignored,
1925                scan_id: 0,
1926            }));
1927            entries_by_path_edits.push(Edit::Insert(entry));
1928        }
1929
1930        self.entries_by_path.edit(entries_by_path_edits, &());
1931        self.entries_by_id.edit(entries_by_id_edits, &());
1932
1933        update.removed_repositories.sort_unstable();
1934        self.repository_entries.retain(|_, entry| {
1935            if let Ok(_) = update
1936                .removed_repositories
1937                .binary_search(&entry.work_directory.to_proto())
1938            {
1939                false
1940            } else {
1941                true
1942            }
1943        });
1944
1945        for repository in update.updated_repositories {
1946            let work_directory_entry: WorkDirectoryEntry =
1947                ProjectEntryId::from_proto(repository.work_directory_id).into();
1948
1949            if let Some(entry) = self.entry_for_id(*work_directory_entry) {
1950                let work_directory = RepositoryWorkDirectory(entry.path.clone());
1951                if self.repository_entries.get(&work_directory).is_some() {
1952                    self.repository_entries.update(&work_directory, |repo| {
1953                        repo.branch = repository.branch.map(Into::into);
1954                    });
1955                } else {
1956                    self.repository_entries.insert(
1957                        work_directory,
1958                        RepositoryEntry {
1959                            work_directory: work_directory_entry,
1960                            branch: repository.branch.map(Into::into),
1961                            // When syncing repository entries from a peer, we don't need
1962                            // the location_in_repo field, since git operations don't happen locally
1963                            // anyway.
1964                            location_in_repo: None,
1965                        },
1966                    )
1967                }
1968            } else {
1969                log::error!("no work directory entry for repository {:?}", repository)
1970            }
1971        }
1972
1973        self.scan_id = update.scan_id as usize;
1974        if update.is_last_update {
1975            self.completed_scan_id = update.scan_id as usize;
1976        }
1977
1978        Ok(())
1979    }
1980
1981    pub fn file_count(&self) -> usize {
1982        self.entries_by_path.summary().file_count
1983    }
1984
1985    pub fn visible_file_count(&self) -> usize {
1986        self.entries_by_path.summary().non_ignored_file_count
1987    }
1988
1989    fn traverse_from_offset(
1990        &self,
1991        include_files: bool,
1992        include_dirs: bool,
1993        include_ignored: bool,
1994        start_offset: usize,
1995    ) -> Traversal {
1996        let mut cursor = self.entries_by_path.cursor();
1997        cursor.seek(
1998            &TraversalTarget::Count {
1999                count: start_offset,
2000                include_files,
2001                include_dirs,
2002                include_ignored,
2003            },
2004            Bias::Right,
2005            &(),
2006        );
2007        Traversal {
2008            cursor,
2009            include_files,
2010            include_dirs,
2011            include_ignored,
2012        }
2013    }
2014
2015    fn traverse_from_path(
2016        &self,
2017        include_files: bool,
2018        include_dirs: bool,
2019        include_ignored: bool,
2020        path: &Path,
2021    ) -> Traversal {
2022        let mut cursor = self.entries_by_path.cursor();
2023        cursor.seek(&TraversalTarget::Path(path), Bias::Left, &());
2024        let mut traversal = Traversal {
2025            cursor,
2026            include_files,
2027            include_dirs,
2028            include_ignored,
2029        };
2030        if traversal.end_offset() == traversal.start_offset() {
2031            traversal.next();
2032        }
2033        traversal
2034    }
2035
2036    pub fn files(&self, include_ignored: bool, start: usize) -> Traversal {
2037        self.traverse_from_offset(true, false, include_ignored, start)
2038    }
2039
2040    pub fn directories(&self, include_ignored: bool, start: usize) -> Traversal {
2041        self.traverse_from_offset(false, true, include_ignored, start)
2042    }
2043
2044    pub fn entries(&self, include_ignored: bool) -> Traversal {
2045        self.traverse_from_offset(true, true, include_ignored, 0)
2046    }
2047
2048    pub fn repositories(&self) -> impl Iterator<Item = (&Arc<Path>, &RepositoryEntry)> {
2049        self.repository_entries
2050            .iter()
2051            .map(|(path, entry)| (&path.0, entry))
2052    }
2053
2054    /// Get the repository whose work directory contains the given path.
2055    pub fn repository_for_work_directory(&self, path: &Path) -> Option<RepositoryEntry> {
2056        self.repository_entries
2057            .get(&RepositoryWorkDirectory(path.into()))
2058            .cloned()
2059    }
2060
2061    /// Get the repository whose work directory contains the given path.
2062    pub fn repository_for_path(&self, path: &Path) -> Option<RepositoryEntry> {
2063        self.repository_and_work_directory_for_path(path)
2064            .map(|e| e.1)
2065    }
2066
2067    pub fn repository_and_work_directory_for_path(
2068        &self,
2069        path: &Path,
2070    ) -> Option<(RepositoryWorkDirectory, RepositoryEntry)> {
2071        self.repository_entries
2072            .iter()
2073            .filter(|(workdir_path, _)| path.starts_with(workdir_path))
2074            .last()
2075            .map(|(path, repo)| (path.clone(), repo.clone()))
2076    }
2077
2078    /// Given an ordered iterator of entries, returns an iterator of those entries,
2079    /// along with their containing git repository.
2080    pub fn entries_with_repositories<'a>(
2081        &'a self,
2082        entries: impl 'a + Iterator<Item = &'a Entry>,
2083    ) -> impl 'a + Iterator<Item = (&'a Entry, Option<&'a RepositoryEntry>)> {
2084        let mut containing_repos = Vec::<(&Arc<Path>, &RepositoryEntry)>::new();
2085        let mut repositories = self.repositories().peekable();
2086        entries.map(move |entry| {
2087            while let Some((repo_path, _)) = containing_repos.last() {
2088                if entry.path.starts_with(repo_path) {
2089                    break;
2090                } else {
2091                    containing_repos.pop();
2092                }
2093            }
2094            while let Some((repo_path, _)) = repositories.peek() {
2095                if entry.path.starts_with(repo_path) {
2096                    containing_repos.push(repositories.next().unwrap());
2097                } else {
2098                    break;
2099                }
2100            }
2101            let repo = containing_repos.last().map(|(_, repo)| *repo);
2102            (entry, repo)
2103        })
2104    }
2105
2106    /// Updates the `git_status` of the given entries such that files'
2107    /// statuses bubble up to their ancestor directories.
2108    pub fn propagate_git_statuses(&self, result: &mut [Entry]) {
2109        let mut cursor = self
2110            .entries_by_path
2111            .cursor::<(TraversalProgress, GitStatuses)>();
2112        let mut entry_stack = Vec::<(usize, GitStatuses)>::new();
2113
2114        let mut result_ix = 0;
2115        loop {
2116            let next_entry = result.get(result_ix);
2117            let containing_entry = entry_stack.last().map(|(ix, _)| &result[*ix]);
2118
2119            let entry_to_finish = match (containing_entry, next_entry) {
2120                (Some(_), None) => entry_stack.pop(),
2121                (Some(containing_entry), Some(next_path)) => {
2122                    if next_path.path.starts_with(&containing_entry.path) {
2123                        None
2124                    } else {
2125                        entry_stack.pop()
2126                    }
2127                }
2128                (None, Some(_)) => None,
2129                (None, None) => break,
2130            };
2131
2132            if let Some((entry_ix, prev_statuses)) = entry_to_finish {
2133                cursor.seek_forward(
2134                    &TraversalTarget::PathSuccessor(&result[entry_ix].path),
2135                    Bias::Left,
2136                    &(),
2137                );
2138
2139                let statuses = cursor.start().1 - prev_statuses;
2140
2141                result[entry_ix].git_status = if statuses.conflict > 0 {
2142                    Some(GitFileStatus::Conflict)
2143                } else if statuses.modified > 0 {
2144                    Some(GitFileStatus::Modified)
2145                } else if statuses.added > 0 {
2146                    Some(GitFileStatus::Added)
2147                } else {
2148                    None
2149                };
2150            } else {
2151                if result[result_ix].is_dir() {
2152                    cursor.seek_forward(
2153                        &TraversalTarget::Path(&result[result_ix].path),
2154                        Bias::Left,
2155                        &(),
2156                    );
2157                    entry_stack.push((result_ix, cursor.start().1));
2158                }
2159                result_ix += 1;
2160            }
2161        }
2162    }
2163
2164    pub fn paths(&self) -> impl Iterator<Item = &Arc<Path>> {
2165        let empty_path = Path::new("");
2166        self.entries_by_path
2167            .cursor::<()>()
2168            .filter(move |entry| entry.path.as_ref() != empty_path)
2169            .map(|entry| &entry.path)
2170    }
2171
2172    pub fn child_entries<'a>(&'a self, parent_path: &'a Path) -> ChildEntriesIter<'a> {
2173        let mut cursor = self.entries_by_path.cursor();
2174        cursor.seek(&TraversalTarget::Path(parent_path), Bias::Right, &());
2175        let traversal = Traversal {
2176            cursor,
2177            include_files: true,
2178            include_dirs: true,
2179            include_ignored: true,
2180        };
2181        ChildEntriesIter {
2182            traversal,
2183            parent_path,
2184        }
2185    }
2186
2187    pub fn root_entry(&self) -> Option<&Entry> {
2188        self.entry_for_path("")
2189    }
2190
2191    pub fn root_name(&self) -> &str {
2192        &self.root_name
2193    }
2194
2195    pub fn root_git_entry(&self) -> Option<RepositoryEntry> {
2196        self.repository_entries
2197            .get(&RepositoryWorkDirectory(Path::new("").into()))
2198            .map(|entry| entry.to_owned())
2199    }
2200
2201    pub fn git_entries(&self) -> impl Iterator<Item = &RepositoryEntry> {
2202        self.repository_entries.values()
2203    }
2204
2205    pub fn scan_id(&self) -> usize {
2206        self.scan_id
2207    }
2208
2209    pub fn entry_for_path(&self, path: impl AsRef<Path>) -> Option<&Entry> {
2210        let path = path.as_ref();
2211        self.traverse_from_path(true, true, true, path)
2212            .entry()
2213            .and_then(|entry| {
2214                if entry.path.as_ref() == path {
2215                    Some(entry)
2216                } else {
2217                    None
2218                }
2219            })
2220    }
2221
2222    pub fn entry_for_id(&self, id: ProjectEntryId) -> Option<&Entry> {
2223        let entry = self.entries_by_id.get(&id, &())?;
2224        self.entry_for_path(&entry.path)
2225    }
2226
2227    pub fn inode_for_path(&self, path: impl AsRef<Path>) -> Option<u64> {
2228        self.entry_for_path(path.as_ref()).map(|e| e.inode)
2229    }
2230}
2231
2232impl LocalSnapshot {
2233    pub fn get_local_repo(&self, repo: &RepositoryEntry) -> Option<&LocalRepositoryEntry> {
2234        self.git_repositories.get(&repo.work_directory.0)
2235    }
2236
2237    pub fn repo_for_path(&self, path: &Path) -> Option<(RepositoryEntry, &LocalRepositoryEntry)> {
2238        let (_, repo_entry) = self.repository_and_work_directory_for_path(path)?;
2239        let work_directory_id = repo_entry.work_directory_id();
2240        Some((repo_entry, self.git_repositories.get(&work_directory_id)?))
2241    }
2242
2243    pub fn local_git_repo(&self, path: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
2244        self.repo_for_path(path)
2245            .map(|(_, entry)| entry.repo_ptr.clone())
2246    }
2247
2248    fn build_update(
2249        &self,
2250        project_id: u64,
2251        worktree_id: u64,
2252        entry_changes: UpdatedEntriesSet,
2253        repo_changes: UpdatedGitRepositoriesSet,
2254    ) -> proto::UpdateWorktree {
2255        let mut updated_entries = Vec::new();
2256        let mut removed_entries = Vec::new();
2257        let mut updated_repositories = Vec::new();
2258        let mut removed_repositories = Vec::new();
2259
2260        for (_, entry_id, path_change) in entry_changes.iter() {
2261            if let PathChange::Removed = path_change {
2262                removed_entries.push(entry_id.0 as u64);
2263            } else if let Some(entry) = self.entry_for_id(*entry_id) {
2264                updated_entries.push(proto::Entry::from(entry));
2265            }
2266        }
2267
2268        for (work_dir_path, change) in repo_changes.iter() {
2269            let new_repo = self
2270                .repository_entries
2271                .get(&RepositoryWorkDirectory(work_dir_path.clone()));
2272            match (&change.old_repository, new_repo) {
2273                (Some(old_repo), Some(new_repo)) => {
2274                    updated_repositories.push(new_repo.build_update(old_repo));
2275                }
2276                (None, Some(new_repo)) => {
2277                    updated_repositories.push(proto::RepositoryEntry::from(new_repo));
2278                }
2279                (Some(old_repo), None) => {
2280                    removed_repositories.push(old_repo.work_directory.0.to_proto());
2281                }
2282                _ => {}
2283            }
2284        }
2285
2286        removed_entries.sort_unstable();
2287        updated_entries.sort_unstable_by_key(|e| e.id);
2288        removed_repositories.sort_unstable();
2289        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2290
2291        // TODO - optimize, knowing that removed_entries are sorted.
2292        removed_entries.retain(|id| updated_entries.binary_search_by_key(id, |e| e.id).is_err());
2293
2294        proto::UpdateWorktree {
2295            project_id,
2296            worktree_id,
2297            abs_path: self.abs_path().to_string_lossy().into(),
2298            root_name: self.root_name().to_string(),
2299            updated_entries,
2300            removed_entries,
2301            scan_id: self.scan_id as u64,
2302            is_last_update: self.completed_scan_id == self.scan_id,
2303            updated_repositories,
2304            removed_repositories,
2305        }
2306    }
2307
2308    fn build_initial_update(&self, project_id: u64, worktree_id: u64) -> proto::UpdateWorktree {
2309        let mut updated_entries = self
2310            .entries_by_path
2311            .iter()
2312            .map(proto::Entry::from)
2313            .collect::<Vec<_>>();
2314        updated_entries.sort_unstable_by_key(|e| e.id);
2315
2316        let mut updated_repositories = self
2317            .repository_entries
2318            .values()
2319            .map(proto::RepositoryEntry::from)
2320            .collect::<Vec<_>>();
2321        updated_repositories.sort_unstable_by_key(|e| e.work_directory_id);
2322
2323        proto::UpdateWorktree {
2324            project_id,
2325            worktree_id,
2326            abs_path: self.abs_path().to_string_lossy().into(),
2327            root_name: self.root_name().to_string(),
2328            updated_entries,
2329            removed_entries: Vec::new(),
2330            scan_id: self.scan_id as u64,
2331            is_last_update: self.completed_scan_id == self.scan_id,
2332            updated_repositories,
2333            removed_repositories: Vec::new(),
2334        }
2335    }
2336
2337    fn insert_entry(&mut self, mut entry: Entry, fs: &dyn Fs) -> Entry {
2338        if entry.is_file() && entry.path.file_name() == Some(&GITIGNORE) {
2339            let abs_path = self.abs_path.join(&entry.path);
2340            match smol::block_on(build_gitignore(&abs_path, fs)) {
2341                Ok(ignore) => {
2342                    self.ignores_by_parent_abs_path
2343                        .insert(abs_path.parent().unwrap().into(), (Arc::new(ignore), true));
2344                }
2345                Err(error) => {
2346                    log::error!(
2347                        "error loading .gitignore file {:?} - {:?}",
2348                        &entry.path,
2349                        error
2350                    );
2351                }
2352            }
2353        }
2354
2355        if entry.kind == EntryKind::PendingDir {
2356            if let Some(existing_entry) =
2357                self.entries_by_path.get(&PathKey(entry.path.clone()), &())
2358            {
2359                entry.kind = existing_entry.kind;
2360            }
2361        }
2362
2363        let scan_id = self.scan_id;
2364        let removed = self.entries_by_path.insert_or_replace(entry.clone(), &());
2365        if let Some(removed) = removed {
2366            if removed.id != entry.id {
2367                self.entries_by_id.remove(&removed.id, &());
2368            }
2369        }
2370        self.entries_by_id.insert_or_replace(
2371            PathEntry {
2372                id: entry.id,
2373                path: entry.path.clone(),
2374                is_ignored: entry.is_ignored,
2375                scan_id,
2376            },
2377            &(),
2378        );
2379
2380        entry
2381    }
2382
2383    fn ancestor_inodes_for_path(&self, path: &Path) -> TreeSet<u64> {
2384        let mut inodes = TreeSet::default();
2385        for ancestor in path.ancestors().skip(1) {
2386            if let Some(entry) = self.entry_for_path(ancestor) {
2387                inodes.insert(entry.inode);
2388            }
2389        }
2390        inodes
2391    }
2392
2393    fn ignore_stack_for_abs_path(&self, abs_path: &Path, is_dir: bool) -> Arc<IgnoreStack> {
2394        let mut new_ignores = Vec::new();
2395        for (index, ancestor) in abs_path.ancestors().enumerate() {
2396            if index > 0 {
2397                if let Some((ignore, _)) = self.ignores_by_parent_abs_path.get(ancestor) {
2398                    new_ignores.push((ancestor, Some(ignore.clone())));
2399                } else {
2400                    new_ignores.push((ancestor, None));
2401                }
2402            }
2403            if ancestor.join(&*DOT_GIT).is_dir() {
2404                break;
2405            }
2406        }
2407
2408        let mut ignore_stack = IgnoreStack::none();
2409        for (parent_abs_path, ignore) in new_ignores.into_iter().rev() {
2410            if ignore_stack.is_abs_path_ignored(parent_abs_path, true) {
2411                ignore_stack = IgnoreStack::all();
2412                break;
2413            } else if let Some(ignore) = ignore {
2414                ignore_stack = ignore_stack.append(parent_abs_path.into(), ignore);
2415            }
2416        }
2417
2418        if ignore_stack.is_abs_path_ignored(abs_path, is_dir) {
2419            ignore_stack = IgnoreStack::all();
2420        }
2421
2422        ignore_stack
2423    }
2424
2425    #[cfg(test)]
2426    pub(crate) fn expanded_entries(&self) -> impl Iterator<Item = &Entry> {
2427        self.entries_by_path
2428            .cursor::<()>()
2429            .filter(|entry| entry.kind == EntryKind::Dir && (entry.is_external || entry.is_ignored))
2430    }
2431
2432    #[cfg(test)]
2433    pub fn check_invariants(&self, git_state: bool) {
2434        use pretty_assertions::assert_eq;
2435
2436        assert_eq!(
2437            self.entries_by_path
2438                .cursor::<()>()
2439                .map(|e| (&e.path, e.id))
2440                .collect::<Vec<_>>(),
2441            self.entries_by_id
2442                .cursor::<()>()
2443                .map(|e| (&e.path, e.id))
2444                .collect::<collections::BTreeSet<_>>()
2445                .into_iter()
2446                .collect::<Vec<_>>(),
2447            "entries_by_path and entries_by_id are inconsistent"
2448        );
2449
2450        let mut files = self.files(true, 0);
2451        let mut visible_files = self.files(false, 0);
2452        for entry in self.entries_by_path.cursor::<()>() {
2453            if entry.is_file() {
2454                assert_eq!(files.next().unwrap().inode, entry.inode);
2455                if !entry.is_ignored && !entry.is_external {
2456                    assert_eq!(visible_files.next().unwrap().inode, entry.inode);
2457                }
2458            }
2459        }
2460
2461        assert!(files.next().is_none());
2462        assert!(visible_files.next().is_none());
2463
2464        let mut bfs_paths = Vec::new();
2465        let mut stack = self
2466            .root_entry()
2467            .map(|e| e.path.as_ref())
2468            .into_iter()
2469            .collect::<Vec<_>>();
2470        while let Some(path) = stack.pop() {
2471            bfs_paths.push(path);
2472            let ix = stack.len();
2473            for child_entry in self.child_entries(path) {
2474                stack.insert(ix, &child_entry.path);
2475            }
2476        }
2477
2478        let dfs_paths_via_iter = self
2479            .entries_by_path
2480            .cursor::<()>()
2481            .map(|e| e.path.as_ref())
2482            .collect::<Vec<_>>();
2483        assert_eq!(bfs_paths, dfs_paths_via_iter);
2484
2485        let dfs_paths_via_traversal = self
2486            .entries(true)
2487            .map(|e| e.path.as_ref())
2488            .collect::<Vec<_>>();
2489        assert_eq!(dfs_paths_via_traversal, dfs_paths_via_iter);
2490
2491        if git_state {
2492            for ignore_parent_abs_path in self.ignores_by_parent_abs_path.keys() {
2493                let ignore_parent_path =
2494                    ignore_parent_abs_path.strip_prefix(&self.abs_path).unwrap();
2495                assert!(self.entry_for_path(&ignore_parent_path).is_some());
2496                assert!(self
2497                    .entry_for_path(ignore_parent_path.join(&*GITIGNORE))
2498                    .is_some());
2499            }
2500        }
2501    }
2502
2503    #[cfg(test)]
2504    pub fn entries_without_ids(&self, include_ignored: bool) -> Vec<(&Path, u64, bool)> {
2505        let mut paths = Vec::new();
2506        for entry in self.entries_by_path.cursor::<()>() {
2507            if include_ignored || !entry.is_ignored {
2508                paths.push((entry.path.as_ref(), entry.inode, entry.is_ignored));
2509            }
2510        }
2511        paths.sort_by(|a, b| a.0.cmp(b.0));
2512        paths
2513    }
2514
2515    pub fn is_path_private(&self, path: &Path) -> bool {
2516        if self.share_private_files {
2517            return false;
2518        }
2519        path.ancestors().any(|ancestor| {
2520            self.private_files
2521                .iter()
2522                .any(|exclude_matcher| exclude_matcher.is_match(&ancestor))
2523        })
2524    }
2525
2526    pub fn is_path_excluded(&self, path: &Path) -> bool {
2527        path.ancestors().any(|path| {
2528            self.file_scan_exclusions
2529                .iter()
2530                .any(|exclude_matcher| exclude_matcher.is_match(&path))
2531        })
2532    }
2533}
2534
2535impl BackgroundScannerState {
2536    fn should_scan_directory(&self, entry: &Entry) -> bool {
2537        (!entry.is_external && !entry.is_ignored)
2538            || entry.path.file_name() == Some(*DOT_GIT)
2539            || self.scanned_dirs.contains(&entry.id) // If we've ever scanned it, keep scanning
2540            || self
2541                .paths_to_scan
2542                .iter()
2543                .any(|p| p.starts_with(&entry.path))
2544            || self
2545                .path_prefixes_to_scan
2546                .iter()
2547                .any(|p| entry.path.starts_with(p))
2548    }
2549
2550    fn enqueue_scan_dir(&self, abs_path: Arc<Path>, entry: &Entry, scan_job_tx: &Sender<ScanJob>) {
2551        let path = entry.path.clone();
2552        let ignore_stack = self.snapshot.ignore_stack_for_abs_path(&abs_path, true);
2553        let mut ancestor_inodes = self.snapshot.ancestor_inodes_for_path(&path);
2554        let mut containing_repository = None;
2555        if !ignore_stack.is_abs_path_ignored(&abs_path, true) {
2556            if let Some((repo_entry, repo)) = self.snapshot.repo_for_path(&path) {
2557                if let Some(workdir_path) = repo_entry.work_directory(&self.snapshot) {
2558                    if let Ok(repo_path) = repo_entry.relativize(&self.snapshot, &path) {
2559                        containing_repository = Some(ScanJobContainingRepository {
2560                            work_directory: workdir_path,
2561                            repository: repo.repo_ptr.clone(),
2562                            staged_statuses: repo.repo_ptr.lock().staged_statuses(&repo_path),
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 staged_statuses = repository.lock().staged_statuses(Path::new(""));
3836                    containing_repository = Some(ScanJobContainingRepository {
3837                        work_directory,
3838                        repository,
3839                        staged_statuses,
3840                    });
3841                }
3842            } else if child_name == *GITIGNORE {
3843                match build_gitignore(&child_abs_path, self.fs.as_ref()).await {
3844                    Ok(ignore) => {
3845                        let ignore = Arc::new(ignore);
3846                        ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
3847                        new_ignore = Some(ignore);
3848                    }
3849                    Err(error) => {
3850                        log::error!(
3851                            "error loading .gitignore file {:?} - {:?}",
3852                            child_name,
3853                            error
3854                        );
3855                    }
3856                }
3857            }
3858
3859            {
3860                let mut state = self.state.lock();
3861                if state.snapshot.is_path_excluded(&child_path) {
3862                    log::debug!("skipping excluded child entry {child_path:?}");
3863                    state.remove_path(&child_path);
3864                    continue;
3865                }
3866            }
3867
3868            let child_metadata = match self.fs.metadata(&child_abs_path).await {
3869                Ok(Some(metadata)) => metadata,
3870                Ok(None) => continue,
3871                Err(err) => {
3872                    log::error!("error processing {child_abs_path:?}: {err:?}");
3873                    continue;
3874                }
3875            };
3876
3877            let mut child_entry = Entry::new(
3878                child_path.clone(),
3879                &child_metadata,
3880                &next_entry_id,
3881                root_char_bag,
3882                None,
3883            );
3884
3885            if job.is_external {
3886                child_entry.is_external = true;
3887            } else if child_metadata.is_symlink {
3888                let canonical_path = match self.fs.canonicalize(&child_abs_path).await {
3889                    Ok(path) => path,
3890                    Err(err) => {
3891                        log::error!(
3892                            "error reading target of symlink {:?}: {:?}",
3893                            child_abs_path,
3894                            err
3895                        );
3896                        continue;
3897                    }
3898                };
3899
3900                // lazily canonicalize the root path in order to determine if
3901                // symlinks point outside of the worktree.
3902                let root_canonical_path = match &root_canonical_path {
3903                    Some(path) => path,
3904                    None => match self.fs.canonicalize(&root_abs_path).await {
3905                        Ok(path) => root_canonical_path.insert(path),
3906                        Err(err) => {
3907                            log::error!("error canonicalizing root {:?}: {:?}", root_abs_path, err);
3908                            continue;
3909                        }
3910                    },
3911                };
3912
3913                if !canonical_path.starts_with(root_canonical_path) {
3914                    child_entry.is_external = true;
3915                }
3916
3917                child_entry.canonical_path = Some(canonical_path);
3918            }
3919
3920            if child_entry.is_dir() {
3921                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, true);
3922
3923                // Avoid recursing until crash in the case of a recursive symlink
3924                if job.ancestor_inodes.contains(&child_entry.inode) {
3925                    new_jobs.push(None);
3926                } else {
3927                    let mut ancestor_inodes = job.ancestor_inodes.clone();
3928                    ancestor_inodes.insert(child_entry.inode);
3929
3930                    new_jobs.push(Some(ScanJob {
3931                        abs_path: child_abs_path.clone(),
3932                        path: child_path,
3933                        is_external: child_entry.is_external,
3934                        ignore_stack: if child_entry.is_ignored {
3935                            IgnoreStack::all()
3936                        } else {
3937                            ignore_stack.clone()
3938                        },
3939                        ancestor_inodes,
3940                        scan_queue: job.scan_queue.clone(),
3941                        containing_repository: containing_repository.clone(),
3942                    }));
3943                }
3944            } else {
3945                child_entry.is_ignored = ignore_stack.is_abs_path_ignored(&child_abs_path, false);
3946                if !child_entry.is_ignored {
3947                    if let Some(repo) = &containing_repository {
3948                        if let Ok(repo_path) = child_entry.path.strip_prefix(&repo.work_directory) {
3949                            if let Some(mtime) = child_entry.mtime {
3950                                let repo_path = RepoPath(repo_path.into());
3951                                child_entry.git_status = combine_git_statuses(
3952                                    repo.staged_statuses.get(&repo_path).copied(),
3953                                    repo.repository.lock().unstaged_status(&repo_path, mtime),
3954                                );
3955                            }
3956                        }
3957                    }
3958                }
3959            }
3960
3961            {
3962                let relative_path = job.path.join(child_name);
3963                let state = self.state.lock();
3964                if state.snapshot.is_path_private(&relative_path) {
3965                    log::debug!("detected private file: {relative_path:?}");
3966                    child_entry.is_private = true;
3967                }
3968                drop(state)
3969            }
3970
3971            new_entries.push(child_entry);
3972        }
3973
3974        let mut state = self.state.lock();
3975
3976        // Identify any subdirectories that should not be scanned.
3977        let mut job_ix = 0;
3978        for entry in &mut new_entries {
3979            state.reuse_entry_id(entry);
3980            if entry.is_dir() {
3981                if state.should_scan_directory(entry) {
3982                    job_ix += 1;
3983                } else {
3984                    log::debug!("defer scanning directory {:?}", entry.path);
3985                    entry.kind = EntryKind::UnloadedDir;
3986                    new_jobs.remove(job_ix);
3987                }
3988            }
3989        }
3990
3991        state.populate_dir(&job.path, new_entries, new_ignore);
3992
3993        for new_job in new_jobs.into_iter().flatten() {
3994            job.scan_queue
3995                .try_send(new_job)
3996                .expect("channel is unbounded");
3997        }
3998
3999        Ok(())
4000    }
4001
4002    async fn reload_entries_for_paths(
4003        &self,
4004        root_abs_path: Arc<Path>,
4005        root_canonical_path: PathBuf,
4006        relative_paths: &[Arc<Path>],
4007        abs_paths: Vec<PathBuf>,
4008        scan_queue_tx: Option<Sender<ScanJob>>,
4009    ) {
4010        let metadata = futures::future::join_all(
4011            abs_paths
4012                .iter()
4013                .map(|abs_path| async move {
4014                    let metadata = self.fs.metadata(abs_path).await?;
4015                    if let Some(metadata) = metadata {
4016                        let canonical_path = self.fs.canonicalize(abs_path).await?;
4017
4018                        // If we're on a case-insensitive filesystem (default on macOS), we want
4019                        // to only ignore metadata for non-symlink files if their absolute-path matches
4020                        // the canonical-path.
4021                        // Because if not, this might be a case-only-renaming (`mv test.txt TEST.TXT`)
4022                        // and we want to ignore the metadata for the old path (`test.txt`) so it's
4023                        // treated as removed.
4024                        if !self.fs_case_sensitive && !metadata.is_symlink {
4025                            let canonical_file_name = canonical_path.file_name();
4026                            let file_name = abs_path.file_name();
4027                            if canonical_file_name != file_name {
4028                                return Ok(None);
4029                            }
4030                        }
4031
4032                        anyhow::Ok(Some((metadata, canonical_path)))
4033                    } else {
4034                        Ok(None)
4035                    }
4036                })
4037                .collect::<Vec<_>>(),
4038        )
4039        .await;
4040
4041        let mut state = self.state.lock();
4042        let doing_recursive_update = scan_queue_tx.is_some();
4043
4044        // Remove any entries for paths that no longer exist or are being recursively
4045        // refreshed. Do this before adding any new entries, so that renames can be
4046        // detected regardless of the order of the paths.
4047        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4048            if matches!(metadata, Ok(None)) || doing_recursive_update {
4049                log::trace!("remove path {:?}", path);
4050                state.remove_path(path);
4051            }
4052        }
4053
4054        for (path, metadata) in relative_paths.iter().zip(metadata.iter()) {
4055            let abs_path: Arc<Path> = root_abs_path.join(&path).into();
4056            match metadata {
4057                Ok(Some((metadata, canonical_path))) => {
4058                    let ignore_stack = state
4059                        .snapshot
4060                        .ignore_stack_for_abs_path(&abs_path, metadata.is_dir);
4061
4062                    let mut fs_entry = Entry::new(
4063                        path.clone(),
4064                        metadata,
4065                        self.next_entry_id.as_ref(),
4066                        state.snapshot.root_char_bag,
4067                        if metadata.is_symlink {
4068                            Some(canonical_path.to_path_buf())
4069                        } else {
4070                            None
4071                        },
4072                    );
4073
4074                    let is_dir = fs_entry.is_dir();
4075                    fs_entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, is_dir);
4076                    fs_entry.is_external = !canonical_path.starts_with(&root_canonical_path);
4077                    fs_entry.is_private = state.snapshot.is_path_private(path);
4078
4079                    if !is_dir && !fs_entry.is_ignored && !fs_entry.is_external {
4080                        if let Some((repo_entry, repo)) = state.snapshot.repo_for_path(path) {
4081                            if let Ok(repo_path) = repo_entry.relativize(&state.snapshot, path) {
4082                                if let Some(mtime) = fs_entry.mtime {
4083                                    let repo = repo.repo_ptr.lock();
4084                                    fs_entry.git_status = repo.status(&repo_path, mtime);
4085                                }
4086                            }
4087                        }
4088                    }
4089
4090                    if let (Some(scan_queue_tx), true) = (&scan_queue_tx, fs_entry.is_dir()) {
4091                        if state.should_scan_directory(&fs_entry) {
4092                            state.enqueue_scan_dir(abs_path, &fs_entry, scan_queue_tx);
4093                        } else {
4094                            fs_entry.kind = EntryKind::UnloadedDir;
4095                        }
4096                    }
4097
4098                    state.insert_entry(fs_entry, self.fs.as_ref());
4099                }
4100                Ok(None) => {
4101                    self.remove_repo_path(path, &mut state.snapshot);
4102                }
4103                Err(err) => {
4104                    // TODO - create a special 'error' entry in the entries tree to mark this
4105                    log::error!("error reading file {abs_path:?} on event: {err:#}");
4106                }
4107            }
4108        }
4109
4110        util::extend_sorted(
4111            &mut state.changed_paths,
4112            relative_paths.iter().cloned(),
4113            usize::MAX,
4114            Ord::cmp,
4115        );
4116    }
4117
4118    fn remove_repo_path(&self, path: &Path, snapshot: &mut LocalSnapshot) -> Option<()> {
4119        if !path
4120            .components()
4121            .any(|component| component.as_os_str() == *DOT_GIT)
4122        {
4123            if let Some(repository) = snapshot.repository_for_work_directory(path) {
4124                let entry = repository.work_directory.0;
4125                snapshot.git_repositories.remove(&entry);
4126                snapshot
4127                    .snapshot
4128                    .repository_entries
4129                    .remove(&RepositoryWorkDirectory(path.into()));
4130                return Some(());
4131            }
4132        }
4133
4134        // TODO statuses
4135        // Track when a .git is removed and iterate over the file system there
4136
4137        Some(())
4138    }
4139
4140    async fn update_ignore_statuses(&self, scan_job_tx: Sender<ScanJob>) {
4141        use futures::FutureExt as _;
4142
4143        let mut snapshot = self.state.lock().snapshot.clone();
4144        let mut ignores_to_update = Vec::new();
4145        let mut ignores_to_delete = Vec::new();
4146        let abs_path = snapshot.abs_path.clone();
4147        for (parent_abs_path, (_, needs_update)) in &mut snapshot.ignores_by_parent_abs_path {
4148            if let Ok(parent_path) = parent_abs_path.strip_prefix(&abs_path) {
4149                if *needs_update {
4150                    *needs_update = false;
4151                    if snapshot.snapshot.entry_for_path(parent_path).is_some() {
4152                        ignores_to_update.push(parent_abs_path.clone());
4153                    }
4154                }
4155
4156                let ignore_path = parent_path.join(&*GITIGNORE);
4157                if snapshot.snapshot.entry_for_path(ignore_path).is_none() {
4158                    ignores_to_delete.push(parent_abs_path.clone());
4159                }
4160            }
4161        }
4162
4163        for parent_abs_path in ignores_to_delete {
4164            snapshot.ignores_by_parent_abs_path.remove(&parent_abs_path);
4165            self.state
4166                .lock()
4167                .snapshot
4168                .ignores_by_parent_abs_path
4169                .remove(&parent_abs_path);
4170        }
4171
4172        let (ignore_queue_tx, ignore_queue_rx) = channel::unbounded();
4173        ignores_to_update.sort_unstable();
4174        let mut ignores_to_update = ignores_to_update.into_iter().peekable();
4175        while let Some(parent_abs_path) = ignores_to_update.next() {
4176            while ignores_to_update
4177                .peek()
4178                .map_or(false, |p| p.starts_with(&parent_abs_path))
4179            {
4180                ignores_to_update.next().unwrap();
4181            }
4182
4183            let ignore_stack = snapshot.ignore_stack_for_abs_path(&parent_abs_path, true);
4184            smol::block_on(ignore_queue_tx.send(UpdateIgnoreStatusJob {
4185                abs_path: parent_abs_path,
4186                ignore_stack,
4187                ignore_queue: ignore_queue_tx.clone(),
4188                scan_queue: scan_job_tx.clone(),
4189            }))
4190            .unwrap();
4191        }
4192        drop(ignore_queue_tx);
4193
4194        self.executor
4195            .scoped(|scope| {
4196                for _ in 0..self.executor.num_cpus() {
4197                    scope.spawn(async {
4198                        loop {
4199                            select_biased! {
4200                                // Process any path refresh requests before moving on to process
4201                                // the queue of ignore statuses.
4202                                request = self.scan_requests_rx.recv().fuse() => {
4203                                    let Ok(request) = request else { break };
4204                                    if !self.process_scan_request(request, true).await {
4205                                        return;
4206                                    }
4207                                }
4208
4209                                // Recursively process directories whose ignores have changed.
4210                                job = ignore_queue_rx.recv().fuse() => {
4211                                    let Ok(job) = job else { break };
4212                                    self.update_ignore_status(job, &snapshot).await;
4213                                }
4214                            }
4215                        }
4216                    });
4217                }
4218            })
4219            .await;
4220    }
4221
4222    async fn update_ignore_status(&self, job: UpdateIgnoreStatusJob, snapshot: &LocalSnapshot) {
4223        log::trace!("update ignore status {:?}", job.abs_path);
4224
4225        let mut ignore_stack = job.ignore_stack;
4226        if let Some((ignore, _)) = snapshot.ignores_by_parent_abs_path.get(&job.abs_path) {
4227            ignore_stack = ignore_stack.append(job.abs_path.clone(), ignore.clone());
4228        }
4229
4230        let mut entries_by_id_edits = Vec::new();
4231        let mut entries_by_path_edits = Vec::new();
4232        let path = job.abs_path.strip_prefix(&snapshot.abs_path).unwrap();
4233        let repo = snapshot.repo_for_path(path);
4234        for mut entry in snapshot.child_entries(path).cloned() {
4235            let was_ignored = entry.is_ignored;
4236            let abs_path: Arc<Path> = snapshot.abs_path().join(&entry.path).into();
4237            entry.is_ignored = ignore_stack.is_abs_path_ignored(&abs_path, entry.is_dir());
4238            if entry.is_dir() {
4239                let child_ignore_stack = if entry.is_ignored {
4240                    IgnoreStack::all()
4241                } else {
4242                    ignore_stack.clone()
4243                };
4244
4245                // Scan any directories that were previously ignored and weren't previously scanned.
4246                if was_ignored && !entry.is_ignored && entry.kind.is_unloaded() {
4247                    let state = self.state.lock();
4248                    if state.should_scan_directory(&entry) {
4249                        state.enqueue_scan_dir(abs_path.clone(), &entry, &job.scan_queue);
4250                    }
4251                }
4252
4253                job.ignore_queue
4254                    .send(UpdateIgnoreStatusJob {
4255                        abs_path: abs_path.clone(),
4256                        ignore_stack: child_ignore_stack,
4257                        ignore_queue: job.ignore_queue.clone(),
4258                        scan_queue: job.scan_queue.clone(),
4259                    })
4260                    .await
4261                    .unwrap();
4262            }
4263
4264            if entry.is_ignored != was_ignored {
4265                let mut path_entry = snapshot.entries_by_id.get(&entry.id, &()).unwrap().clone();
4266                path_entry.scan_id = snapshot.scan_id;
4267                path_entry.is_ignored = entry.is_ignored;
4268                if !entry.is_dir() && !entry.is_ignored && !entry.is_external {
4269                    if let Some((ref repo_entry, local_repo)) = repo {
4270                        if let Some(mtime) = &entry.mtime {
4271                            if let Ok(repo_path) = repo_entry.relativize(&snapshot, &entry.path) {
4272                                let repo = local_repo.repo_ptr.lock();
4273                                entry.git_status = repo.status(&repo_path, *mtime);
4274                            }
4275                        }
4276                    }
4277                }
4278                entries_by_id_edits.push(Edit::Insert(path_entry));
4279                entries_by_path_edits.push(Edit::Insert(entry));
4280            }
4281        }
4282
4283        let state = &mut self.state.lock();
4284        for edit in &entries_by_path_edits {
4285            if let Edit::Insert(entry) = edit {
4286                if let Err(ix) = state.changed_paths.binary_search(&entry.path) {
4287                    state.changed_paths.insert(ix, entry.path.clone());
4288                }
4289            }
4290        }
4291
4292        state
4293            .snapshot
4294            .entries_by_path
4295            .edit(entries_by_path_edits, &());
4296        state.snapshot.entries_by_id.edit(entries_by_id_edits, &());
4297    }
4298
4299    async fn update_git_repositories(&self, dot_git_paths: Vec<PathBuf>) {
4300        log::debug!("reloading repositories: {dot_git_paths:?}");
4301
4302        let (update_job_tx, update_job_rx) = channel::unbounded();
4303        {
4304            let mut state = self.state.lock();
4305            let scan_id = state.snapshot.scan_id;
4306            for dot_git_dir in dot_git_paths {
4307                let existing_repository_entry =
4308                    state
4309                        .snapshot
4310                        .git_repositories
4311                        .iter()
4312                        .find_map(|(entry_id, repo)| {
4313                            (repo.git_dir_path.as_ref() == dot_git_dir)
4314                                .then(|| (*entry_id, repo.clone()))
4315                        });
4316
4317                let (work_dir, repository) = match existing_repository_entry {
4318                    None => {
4319                        match state.build_git_repository(dot_git_dir.into(), self.fs.as_ref()) {
4320                            Some(output) => output,
4321                            None => continue,
4322                        }
4323                    }
4324                    Some((entry_id, repository)) => {
4325                        if repository.git_dir_scan_id == scan_id {
4326                            continue;
4327                        }
4328                        let Some(work_dir) = state
4329                            .snapshot
4330                            .entry_for_id(entry_id)
4331                            .map(|entry| RepositoryWorkDirectory(entry.path.clone()))
4332                        else {
4333                            continue;
4334                        };
4335
4336                        log::info!("reload git repository {dot_git_dir:?}");
4337                        let repo = repository.repo_ptr.lock();
4338                        let branch = repo.branch_name();
4339                        repo.reload_index();
4340
4341                        state
4342                            .snapshot
4343                            .git_repositories
4344                            .update(&entry_id, |entry| entry.git_dir_scan_id = scan_id);
4345                        state
4346                            .snapshot
4347                            .snapshot
4348                            .repository_entries
4349                            .update(&work_dir, |entry| entry.branch = branch.map(Into::into));
4350                        (work_dir, repository.repo_ptr.clone())
4351                    }
4352                };
4353
4354                let staged_statuses = repository.lock().staged_statuses(Path::new(""));
4355                let mut files =
4356                    state
4357                        .snapshot
4358                        .traverse_from_path(true, false, false, work_dir.0.as_ref());
4359                let mut start_path = work_dir.0.clone();
4360                while start_path.starts_with(&work_dir.0) {
4361                    files.advance_by(GIT_STATUS_UPDATE_BATCH_SIZE);
4362                    let end_path = files.entry().map(|e| e.path.clone());
4363                    smol::block_on(update_job_tx.send(UpdateGitStatusesJob {
4364                        start_path: start_path.clone(),
4365                        end_path: end_path.clone(),
4366                        containing_repository: ScanJobContainingRepository {
4367                            work_directory: work_dir.clone(),
4368                            repository: repository.clone(),
4369                            staged_statuses: staged_statuses.clone(),
4370                        },
4371                    }))
4372                    .unwrap();
4373                    if let Some(end_path) = end_path {
4374                        start_path = end_path;
4375                    } else {
4376                        break;
4377                    }
4378                }
4379            }
4380
4381            // Remove any git repositories whose .git entry no longer exists.
4382            let snapshot = &mut state.snapshot;
4383            let mut ids_to_preserve = HashSet::default();
4384            for (&work_directory_id, entry) in snapshot.git_repositories.iter() {
4385                let exists_in_snapshot = snapshot
4386                    .entry_for_id(work_directory_id)
4387                    .map_or(false, |entry| {
4388                        snapshot.entry_for_path(entry.path.join(*DOT_GIT)).is_some()
4389                    });
4390                if exists_in_snapshot {
4391                    ids_to_preserve.insert(work_directory_id);
4392                } else {
4393                    let git_dir_abs_path = snapshot.abs_path().join(&entry.git_dir_path);
4394                    let git_dir_excluded = snapshot.is_path_excluded(&entry.git_dir_path);
4395                    if git_dir_excluded
4396                        && !matches!(
4397                            smol::block_on(self.fs.metadata(&git_dir_abs_path)),
4398                            Ok(None)
4399                        )
4400                    {
4401                        ids_to_preserve.insert(work_directory_id);
4402                    }
4403                }
4404            }
4405
4406            snapshot
4407                .git_repositories
4408                .retain(|work_directory_id, _| ids_to_preserve.contains(work_directory_id));
4409            snapshot
4410                .repository_entries
4411                .retain(|_, entry| ids_to_preserve.contains(&entry.work_directory.0));
4412        }
4413        drop(update_job_tx);
4414
4415        self.executor
4416            .scoped(|scope| {
4417                // Git status updates are currently not very parallelizable,
4418                // because they need to lock the git repository. Limit the number
4419                // of workers so that
4420                for _ in 0..self.executor.num_cpus().min(3) {
4421                    scope.spawn(async {
4422                        let mut entries = Vec::with_capacity(GIT_STATUS_UPDATE_BATCH_SIZE);
4423                        loop {
4424                            select_biased! {
4425                                // Process any path refresh requests before moving on to process
4426                                // the queue of ignore statuses.
4427                                request = self.scan_requests_rx.recv().fuse() => {
4428                                    let Ok(request) = request else { break };
4429                                    if !self.process_scan_request(request, true).await {
4430                                        return;
4431                                    }
4432                                }
4433
4434                                // Process git status updates in batches.
4435                                job = update_job_rx.recv().fuse() => {
4436                                    let Ok(job) = job else { break };
4437                                    self.update_git_statuses(job, &mut entries);
4438                                }
4439                            }
4440                        }
4441                    });
4442                }
4443            })
4444            .await;
4445    }
4446
4447    /// Update the git statuses for a given batch of entries.
4448    fn update_git_statuses(&self, job: UpdateGitStatusesJob, entries: &mut Vec<Entry>) {
4449        let t0 = Instant::now();
4450        let repo_work_dir = &job.containing_repository.work_directory;
4451        let state = self.state.lock();
4452        let Some(repo_entry) = state
4453            .snapshot
4454            .repository_entries
4455            .get(&repo_work_dir)
4456            .cloned()
4457        else {
4458            return;
4459        };
4460
4461        // Retrieve a batch of entries for this job, and then release the state lock.
4462        entries.clear();
4463        for entry in state
4464            .snapshot
4465            .traverse_from_path(true, false, false, &job.start_path)
4466        {
4467            if job
4468                .end_path
4469                .as_ref()
4470                .map_or(false, |end| &entry.path >= end)
4471                || !entry.path.starts_with(&repo_work_dir)
4472            {
4473                break;
4474            }
4475            entries.push(entry.clone());
4476        }
4477        drop(state);
4478
4479        // Determine which entries in this batch have changed their git status.
4480        let mut edits = vec![];
4481        for entry in entries.iter() {
4482            let Ok(repo_path) = entry.path.strip_prefix(&repo_work_dir) else {
4483                continue;
4484            };
4485            let Some(mtime) = entry.mtime else {
4486                continue;
4487            };
4488            let repo_path = RepoPath(if let Some(location) = &repo_entry.location_in_repo {
4489                location.join(repo_path)
4490            } else {
4491                repo_path.to_path_buf()
4492            });
4493            let git_status = combine_git_statuses(
4494                job.containing_repository
4495                    .staged_statuses
4496                    .get(&repo_path)
4497                    .copied(),
4498                job.containing_repository
4499                    .repository
4500                    .lock()
4501                    .unstaged_status(&repo_path, mtime),
4502            );
4503            if entry.git_status != git_status {
4504                let mut entry = entry.clone();
4505                entry.git_status = git_status;
4506                edits.push(Edit::Insert(entry));
4507            }
4508        }
4509
4510        // Apply the git status changes.
4511        let mut state = self.state.lock();
4512        let path_changes = edits.iter().map(|edit| {
4513            if let Edit::Insert(entry) = edit {
4514                entry.path.clone()
4515            } else {
4516                unreachable!()
4517            }
4518        });
4519        util::extend_sorted(&mut state.changed_paths, path_changes, usize::MAX, Ord::cmp);
4520        state.snapshot.entries_by_path.edit(edits, &());
4521
4522        log::trace!(
4523            "refreshed git status of {} entries starting with {} in {:?}",
4524            entries.len(),
4525            job.start_path.display(),
4526            t0.elapsed()
4527        );
4528    }
4529
4530    fn build_change_set(
4531        &self,
4532        old_snapshot: &Snapshot,
4533        new_snapshot: &Snapshot,
4534        event_paths: &[Arc<Path>],
4535    ) -> UpdatedEntriesSet {
4536        use BackgroundScannerPhase::*;
4537        use PathChange::{Added, AddedOrUpdated, Loaded, Removed, Updated};
4538
4539        // Identify which paths have changed. Use the known set of changed
4540        // parent paths to optimize the search.
4541        let mut changes = Vec::new();
4542        let mut old_paths = old_snapshot.entries_by_path.cursor::<PathKey>();
4543        let mut new_paths = new_snapshot.entries_by_path.cursor::<PathKey>();
4544        let mut last_newly_loaded_dir_path = None;
4545        old_paths.next(&());
4546        new_paths.next(&());
4547        for path in event_paths {
4548            let path = PathKey(path.clone());
4549            if old_paths.item().map_or(false, |e| e.path < path.0) {
4550                old_paths.seek_forward(&path, Bias::Left, &());
4551            }
4552            if new_paths.item().map_or(false, |e| e.path < path.0) {
4553                new_paths.seek_forward(&path, Bias::Left, &());
4554            }
4555            loop {
4556                match (old_paths.item(), new_paths.item()) {
4557                    (Some(old_entry), Some(new_entry)) => {
4558                        if old_entry.path > path.0
4559                            && new_entry.path > path.0
4560                            && !old_entry.path.starts_with(&path.0)
4561                            && !new_entry.path.starts_with(&path.0)
4562                        {
4563                            break;
4564                        }
4565
4566                        match Ord::cmp(&old_entry.path, &new_entry.path) {
4567                            Ordering::Less => {
4568                                changes.push((old_entry.path.clone(), old_entry.id, Removed));
4569                                old_paths.next(&());
4570                            }
4571                            Ordering::Equal => {
4572                                if self.phase == EventsReceivedDuringInitialScan {
4573                                    if old_entry.id != new_entry.id {
4574                                        changes.push((
4575                                            old_entry.path.clone(),
4576                                            old_entry.id,
4577                                            Removed,
4578                                        ));
4579                                    }
4580                                    // If the worktree was not fully initialized when this event was generated,
4581                                    // we can't know whether this entry was added during the scan or whether
4582                                    // it was merely updated.
4583                                    changes.push((
4584                                        new_entry.path.clone(),
4585                                        new_entry.id,
4586                                        AddedOrUpdated,
4587                                    ));
4588                                } else if old_entry.id != new_entry.id {
4589                                    changes.push((old_entry.path.clone(), old_entry.id, Removed));
4590                                    changes.push((new_entry.path.clone(), new_entry.id, Added));
4591                                } else if old_entry != new_entry {
4592                                    if old_entry.kind.is_unloaded() {
4593                                        last_newly_loaded_dir_path = Some(&new_entry.path);
4594                                        changes.push((
4595                                            new_entry.path.clone(),
4596                                            new_entry.id,
4597                                            Loaded,
4598                                        ));
4599                                    } else {
4600                                        changes.push((
4601                                            new_entry.path.clone(),
4602                                            new_entry.id,
4603                                            Updated,
4604                                        ));
4605                                    }
4606                                }
4607                                old_paths.next(&());
4608                                new_paths.next(&());
4609                            }
4610                            Ordering::Greater => {
4611                                let is_newly_loaded = self.phase == InitialScan
4612                                    || last_newly_loaded_dir_path
4613                                        .as_ref()
4614                                        .map_or(false, |dir| new_entry.path.starts_with(&dir));
4615                                changes.push((
4616                                    new_entry.path.clone(),
4617                                    new_entry.id,
4618                                    if is_newly_loaded { Loaded } else { Added },
4619                                ));
4620                                new_paths.next(&());
4621                            }
4622                        }
4623                    }
4624                    (Some(old_entry), None) => {
4625                        changes.push((old_entry.path.clone(), old_entry.id, Removed));
4626                        old_paths.next(&());
4627                    }
4628                    (None, Some(new_entry)) => {
4629                        let is_newly_loaded = self.phase == InitialScan
4630                            || last_newly_loaded_dir_path
4631                                .as_ref()
4632                                .map_or(false, |dir| new_entry.path.starts_with(&dir));
4633                        changes.push((
4634                            new_entry.path.clone(),
4635                            new_entry.id,
4636                            if is_newly_loaded { Loaded } else { Added },
4637                        ));
4638                        new_paths.next(&());
4639                    }
4640                    (None, None) => break,
4641                }
4642            }
4643        }
4644
4645        changes.into()
4646    }
4647
4648    async fn progress_timer(&self, running: bool) {
4649        if !running {
4650            return futures::future::pending().await;
4651        }
4652
4653        #[cfg(any(test, feature = "test-support"))]
4654        if self.fs.is_fake() {
4655            return self.executor.simulate_random_delay().await;
4656        }
4657
4658        smol::Timer::after(FS_WATCH_LATENCY).await;
4659    }
4660}
4661
4662fn char_bag_for_path(root_char_bag: CharBag, path: &Path) -> CharBag {
4663    let mut result = root_char_bag;
4664    result.extend(
4665        path.to_string_lossy()
4666            .chars()
4667            .map(|c| c.to_ascii_lowercase()),
4668    );
4669    result
4670}
4671
4672struct ScanJob {
4673    abs_path: Arc<Path>,
4674    path: Arc<Path>,
4675    ignore_stack: Arc<IgnoreStack>,
4676    scan_queue: Sender<ScanJob>,
4677    ancestor_inodes: TreeSet<u64>,
4678    is_external: bool,
4679    containing_repository: Option<ScanJobContainingRepository>,
4680}
4681
4682#[derive(Clone)]
4683struct ScanJobContainingRepository {
4684    work_directory: RepositoryWorkDirectory,
4685    repository: Arc<Mutex<dyn GitRepository>>,
4686    staged_statuses: TreeMap<RepoPath, GitFileStatus>,
4687}
4688
4689struct UpdateIgnoreStatusJob {
4690    abs_path: Arc<Path>,
4691    ignore_stack: Arc<IgnoreStack>,
4692    ignore_queue: Sender<UpdateIgnoreStatusJob>,
4693    scan_queue: Sender<ScanJob>,
4694}
4695
4696struct UpdateGitStatusesJob {
4697    start_path: Arc<Path>,
4698    end_path: Option<Arc<Path>>,
4699    containing_repository: ScanJobContainingRepository,
4700}
4701
4702pub trait WorktreeModelHandle {
4703    #[cfg(any(test, feature = "test-support"))]
4704    fn flush_fs_events<'a>(
4705        &self,
4706        cx: &'a mut gpui::TestAppContext,
4707    ) -> futures::future::LocalBoxFuture<'a, ()>;
4708
4709    #[cfg(any(test, feature = "test-support"))]
4710    fn flush_fs_events_in_root_git_repository<'a>(
4711        &self,
4712        cx: &'a mut gpui::TestAppContext,
4713    ) -> futures::future::LocalBoxFuture<'a, ()>;
4714}
4715
4716impl WorktreeModelHandle for Model<Worktree> {
4717    // When the worktree's FS event stream sometimes delivers "redundant" events for FS changes that
4718    // occurred before the worktree was constructed. These events can cause the worktree to perform
4719    // extra directory scans, and emit extra scan-state notifications.
4720    //
4721    // This function mutates the worktree's directory and waits for those mutations to be picked up,
4722    // to ensure that all redundant FS events have already been processed.
4723    #[cfg(any(test, feature = "test-support"))]
4724    fn flush_fs_events<'a>(
4725        &self,
4726        cx: &'a mut gpui::TestAppContext,
4727    ) -> futures::future::LocalBoxFuture<'a, ()> {
4728        let file_name = "fs-event-sentinel";
4729
4730        let tree = self.clone();
4731        let (fs, root_path) = self.update(cx, |tree, _| {
4732            let tree = tree.as_local().unwrap();
4733            (tree.fs.clone(), tree.abs_path().clone())
4734        });
4735
4736        async move {
4737            fs.create_file(&root_path.join(file_name), Default::default())
4738                .await
4739                .unwrap();
4740
4741            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
4742                .await;
4743
4744            fs.remove_file(&root_path.join(file_name), Default::default())
4745                .await
4746                .unwrap();
4747            cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
4748                .await;
4749
4750            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4751                .await;
4752        }
4753        .boxed_local()
4754    }
4755
4756    // This function is similar to flush_fs_events, except that it waits for events to be flushed in
4757    // the .git folder of the root repository.
4758    // The reason for its existence is that a repository's .git folder might live *outside* of the
4759    // worktree and thus its FS events might go through a different path.
4760    // In order to flush those, we need to create artificial events in the .git folder and wait
4761    // for the repository to be reloaded.
4762    #[cfg(any(test, feature = "test-support"))]
4763    fn flush_fs_events_in_root_git_repository<'a>(
4764        &self,
4765        cx: &'a mut gpui::TestAppContext,
4766    ) -> futures::future::LocalBoxFuture<'a, ()> {
4767        let file_name = "fs-event-sentinel";
4768
4769        let tree = self.clone();
4770        let (fs, root_path, mut git_dir_scan_id) = self.update(cx, |tree, _| {
4771            let tree = tree.as_local().unwrap();
4772            let root_entry = tree.root_git_entry().unwrap();
4773            let local_repo_entry = tree.get_local_repo(&root_entry).unwrap();
4774            (
4775                tree.fs.clone(),
4776                local_repo_entry.git_dir_path.clone(),
4777                local_repo_entry.git_dir_scan_id,
4778            )
4779        });
4780
4781        let scan_id_increased = |tree: &mut Worktree, git_dir_scan_id: &mut usize| {
4782            let root_entry = tree.root_git_entry().unwrap();
4783            let local_repo_entry = tree
4784                .as_local()
4785                .unwrap()
4786                .get_local_repo(&root_entry)
4787                .unwrap();
4788
4789            if local_repo_entry.git_dir_scan_id > *git_dir_scan_id {
4790                *git_dir_scan_id = local_repo_entry.git_dir_scan_id;
4791                true
4792            } else {
4793                false
4794            }
4795        };
4796
4797        async move {
4798            fs.create_file(&root_path.join(file_name), Default::default())
4799                .await
4800                .unwrap();
4801
4802            cx.condition(&tree, |tree, _| {
4803                scan_id_increased(tree, &mut git_dir_scan_id)
4804            })
4805            .await;
4806
4807            fs.remove_file(&root_path.join(file_name), Default::default())
4808                .await
4809                .unwrap();
4810
4811            cx.condition(&tree, |tree, _| {
4812                scan_id_increased(tree, &mut git_dir_scan_id)
4813            })
4814            .await;
4815
4816            cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
4817                .await;
4818        }
4819        .boxed_local()
4820    }
4821}
4822
4823#[derive(Clone, Debug)]
4824struct TraversalProgress<'a> {
4825    max_path: &'a Path,
4826    count: usize,
4827    non_ignored_count: usize,
4828    file_count: usize,
4829    non_ignored_file_count: usize,
4830}
4831
4832impl<'a> TraversalProgress<'a> {
4833    fn count(&self, include_files: bool, include_dirs: bool, include_ignored: bool) -> usize {
4834        match (include_files, include_dirs, include_ignored) {
4835            (true, true, true) => self.count,
4836            (true, true, false) => self.non_ignored_count,
4837            (true, false, true) => self.file_count,
4838            (true, false, false) => self.non_ignored_file_count,
4839            (false, true, true) => self.count - self.file_count,
4840            (false, true, false) => self.non_ignored_count - self.non_ignored_file_count,
4841            (false, false, _) => 0,
4842        }
4843    }
4844}
4845
4846impl<'a> sum_tree::Dimension<'a, EntrySummary> for TraversalProgress<'a> {
4847    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4848        self.max_path = summary.max_path.as_ref();
4849        self.count += summary.count;
4850        self.non_ignored_count += summary.non_ignored_count;
4851        self.file_count += summary.file_count;
4852        self.non_ignored_file_count += summary.non_ignored_file_count;
4853    }
4854}
4855
4856impl<'a> Default for TraversalProgress<'a> {
4857    fn default() -> Self {
4858        Self {
4859            max_path: Path::new(""),
4860            count: 0,
4861            non_ignored_count: 0,
4862            file_count: 0,
4863            non_ignored_file_count: 0,
4864        }
4865    }
4866}
4867
4868#[derive(Clone, Debug, Default, Copy)]
4869struct GitStatuses {
4870    added: usize,
4871    modified: usize,
4872    conflict: usize,
4873}
4874
4875impl AddAssign for GitStatuses {
4876    fn add_assign(&mut self, rhs: Self) {
4877        self.added += rhs.added;
4878        self.modified += rhs.modified;
4879        self.conflict += rhs.conflict;
4880    }
4881}
4882
4883impl Sub for GitStatuses {
4884    type Output = GitStatuses;
4885
4886    fn sub(self, rhs: Self) -> Self::Output {
4887        GitStatuses {
4888            added: self.added - rhs.added,
4889            modified: self.modified - rhs.modified,
4890            conflict: self.conflict - rhs.conflict,
4891        }
4892    }
4893}
4894
4895impl<'a> sum_tree::Dimension<'a, EntrySummary> for GitStatuses {
4896    fn add_summary(&mut self, summary: &'a EntrySummary, _: &()) {
4897        *self += summary.statuses
4898    }
4899}
4900
4901pub struct Traversal<'a> {
4902    cursor: sum_tree::Cursor<'a, Entry, TraversalProgress<'a>>,
4903    include_ignored: bool,
4904    include_files: bool,
4905    include_dirs: bool,
4906}
4907
4908impl<'a> Traversal<'a> {
4909    pub fn advance(&mut self) -> bool {
4910        self.advance_by(1)
4911    }
4912
4913    pub fn advance_by(&mut self, count: usize) -> bool {
4914        self.cursor.seek_forward(
4915            &TraversalTarget::Count {
4916                count: self.end_offset() + count,
4917                include_dirs: self.include_dirs,
4918                include_files: self.include_files,
4919                include_ignored: self.include_ignored,
4920            },
4921            Bias::Left,
4922            &(),
4923        )
4924    }
4925
4926    pub fn advance_to_sibling(&mut self) -> bool {
4927        while let Some(entry) = self.cursor.item() {
4928            self.cursor.seek_forward(
4929                &TraversalTarget::PathSuccessor(&entry.path),
4930                Bias::Left,
4931                &(),
4932            );
4933            if let Some(entry) = self.cursor.item() {
4934                if (self.include_files || !entry.is_file())
4935                    && (self.include_dirs || !entry.is_dir())
4936                    && (self.include_ignored || !entry.is_ignored)
4937                {
4938                    return true;
4939                }
4940            }
4941        }
4942        false
4943    }
4944
4945    pub fn entry(&self) -> Option<&'a Entry> {
4946        self.cursor.item()
4947    }
4948
4949    pub fn start_offset(&self) -> usize {
4950        self.cursor
4951            .start()
4952            .count(self.include_files, self.include_dirs, self.include_ignored)
4953    }
4954
4955    pub fn end_offset(&self) -> usize {
4956        self.cursor
4957            .end(&())
4958            .count(self.include_files, self.include_dirs, self.include_ignored)
4959    }
4960}
4961
4962impl<'a> Iterator for Traversal<'a> {
4963    type Item = &'a Entry;
4964
4965    fn next(&mut self) -> Option<Self::Item> {
4966        if let Some(item) = self.entry() {
4967            self.advance();
4968            Some(item)
4969        } else {
4970            None
4971        }
4972    }
4973}
4974
4975#[derive(Debug)]
4976enum TraversalTarget<'a> {
4977    Path(&'a Path),
4978    PathSuccessor(&'a Path),
4979    Count {
4980        count: usize,
4981        include_files: bool,
4982        include_ignored: bool,
4983        include_dirs: bool,
4984    },
4985}
4986
4987impl<'a, 'b> SeekTarget<'a, EntrySummary, TraversalProgress<'a>> for TraversalTarget<'b> {
4988    fn cmp(&self, cursor_location: &TraversalProgress<'a>, _: &()) -> Ordering {
4989        match self {
4990            TraversalTarget::Path(path) => path.cmp(&cursor_location.max_path),
4991            TraversalTarget::PathSuccessor(path) => {
4992                if cursor_location.max_path.starts_with(path) {
4993                    Ordering::Greater
4994                } else {
4995                    Ordering::Equal
4996                }
4997            }
4998            TraversalTarget::Count {
4999                count,
5000                include_files,
5001                include_dirs,
5002                include_ignored,
5003            } => Ord::cmp(
5004                count,
5005                &cursor_location.count(*include_files, *include_dirs, *include_ignored),
5006            ),
5007        }
5008    }
5009}
5010
5011impl<'a, 'b> SeekTarget<'a, EntrySummary, (TraversalProgress<'a>, GitStatuses)>
5012    for TraversalTarget<'b>
5013{
5014    fn cmp(&self, cursor_location: &(TraversalProgress<'a>, GitStatuses), _: &()) -> Ordering {
5015        self.cmp(&cursor_location.0, &())
5016    }
5017}
5018
5019pub struct ChildEntriesIter<'a> {
5020    parent_path: &'a Path,
5021    traversal: Traversal<'a>,
5022}
5023
5024impl<'a> Iterator for ChildEntriesIter<'a> {
5025    type Item = &'a Entry;
5026
5027    fn next(&mut self) -> Option<Self::Item> {
5028        if let Some(item) = self.traversal.entry() {
5029            if item.path.starts_with(&self.parent_path) {
5030                self.traversal.advance_to_sibling();
5031                return Some(item);
5032            }
5033        }
5034        None
5035    }
5036}
5037
5038impl<'a> From<&'a Entry> for proto::Entry {
5039    fn from(entry: &'a Entry) -> Self {
5040        Self {
5041            id: entry.id.to_proto(),
5042            is_dir: entry.is_dir(),
5043            path: entry.path.to_string_lossy().into(),
5044            inode: entry.inode,
5045            mtime: entry.mtime.map(|time| time.into()),
5046            is_symlink: entry.is_symlink,
5047            is_ignored: entry.is_ignored,
5048            is_external: entry.is_external,
5049            git_status: entry.git_status.map(git_status_to_proto),
5050        }
5051    }
5052}
5053
5054impl<'a> TryFrom<(&'a CharBag, proto::Entry)> for Entry {
5055    type Error = anyhow::Error;
5056
5057    fn try_from((root_char_bag, entry): (&'a CharBag, proto::Entry)) -> Result<Self> {
5058        let kind = if entry.is_dir {
5059            EntryKind::Dir
5060        } else {
5061            let mut char_bag = *root_char_bag;
5062            char_bag.extend(entry.path.chars().map(|c| c.to_ascii_lowercase()));
5063            EntryKind::File(char_bag)
5064        };
5065        let path: Arc<Path> = PathBuf::from(entry.path).into();
5066        Ok(Entry {
5067            id: ProjectEntryId::from_proto(entry.id),
5068            kind,
5069            path,
5070            inode: entry.inode,
5071            mtime: entry.mtime.map(|time| time.into()),
5072            canonical_path: None,
5073            is_ignored: entry.is_ignored,
5074            is_external: entry.is_external,
5075            git_status: git_status_from_proto(entry.git_status),
5076            is_private: false,
5077            is_symlink: entry.is_symlink,
5078        })
5079    }
5080}
5081
5082fn combine_git_statuses(
5083    staged: Option<GitFileStatus>,
5084    unstaged: Option<GitFileStatus>,
5085) -> Option<GitFileStatus> {
5086    if let Some(staged) = staged {
5087        if let Some(unstaged) = unstaged {
5088            if unstaged == staged {
5089                Some(staged)
5090            } else {
5091                Some(GitFileStatus::Modified)
5092            }
5093        } else {
5094            Some(staged)
5095        }
5096    } else {
5097        unstaged
5098    }
5099}
5100
5101fn git_status_from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
5102    git_status.and_then(|status| {
5103        proto::GitStatus::from_i32(status).map(|status| match status {
5104            proto::GitStatus::Added => GitFileStatus::Added,
5105            proto::GitStatus::Modified => GitFileStatus::Modified,
5106            proto::GitStatus::Conflict => GitFileStatus::Conflict,
5107        })
5108    })
5109}
5110
5111fn git_status_to_proto(status: GitFileStatus) -> i32 {
5112    match status {
5113        GitFileStatus::Added => proto::GitStatus::Added as i32,
5114        GitFileStatus::Modified => proto::GitStatus::Modified as i32,
5115        GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
5116    }
5117}
5118
5119#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
5120pub struct ProjectEntryId(usize);
5121
5122impl ProjectEntryId {
5123    pub const MAX: Self = Self(usize::MAX);
5124    pub const MIN: Self = Self(usize::MIN);
5125
5126    pub fn new(counter: &AtomicUsize) -> Self {
5127        Self(counter.fetch_add(1, SeqCst))
5128    }
5129
5130    pub fn from_proto(id: u64) -> Self {
5131        Self(id as usize)
5132    }
5133
5134    pub fn to_proto(&self) -> u64 {
5135        self.0 as u64
5136    }
5137
5138    pub fn to_usize(&self) -> usize {
5139        self.0
5140    }
5141}
5142
5143#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
5144pub struct DiagnosticSummary {
5145    pub error_count: usize,
5146    pub warning_count: usize,
5147}
5148
5149impl DiagnosticSummary {
5150    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
5151        let mut this = Self {
5152            error_count: 0,
5153            warning_count: 0,
5154        };
5155
5156        for entry in diagnostics {
5157            if entry.diagnostic.is_primary {
5158                match entry.diagnostic.severity {
5159                    DiagnosticSeverity::ERROR => this.error_count += 1,
5160                    DiagnosticSeverity::WARNING => this.warning_count += 1,
5161                    _ => {}
5162                }
5163            }
5164        }
5165
5166        this
5167    }
5168
5169    pub fn is_empty(&self) -> bool {
5170        self.error_count == 0 && self.warning_count == 0
5171    }
5172
5173    pub fn to_proto(
5174        &self,
5175        language_server_id: LanguageServerId,
5176        path: &Path,
5177    ) -> proto::DiagnosticSummary {
5178        proto::DiagnosticSummary {
5179            path: path.to_string_lossy().to_string(),
5180            language_server_id: language_server_id.0 as u64,
5181            error_count: self.error_count as u32,
5182            warning_count: self.warning_count as u32,
5183        }
5184    }
5185}