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