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